﻿
define(["ecp.service", "ecp.utils.des", "print.bean", "ecp.component.comboBox", "qzz.icheckbox"],function (rs, des) {
	
	var qzz = window.qzz;
	
    qzz.space("print");
	
	qzz.print.ecpBean = qzz.Class(qzz.print.bean, {
		
		_create : function(option){
		    this.base();
		},
		initScheme : function(params) {
	        
			var hasMainTable = params["hasMainTable"];
			if(params.printMs != null && params.printMs !== "") {
			     this.setPrinter(params.printMs);
			}			
			var tableFillModel = 2;
			this.option.subTableNextPage = false;
			this.option.subGridOnOnePage = false;
			this.option.extrabzprint = false;
			this.option.noWorkFlow = false;
			//每毫米多少象素
			var cZoomValue = 1;
			var setParams = {};
			this.option.hasModelPage = false;
	        if(params != null && params.faVo != null 
	        	&& params.faVo.dycs != null && params.faVo.dycs !== "") {
	        	var faXml = new printXmlDoc();
	        	var xmlStr = params.faVo.dycs;
	        	if(xmlStr.indexOf("<?xml") < 0) {
	        		xmlStr = des.decodeBase64(xmlStr, true); //encodeBase64
	        	}
				faXml.setXml(xmlStr);				
				var commoncs = faXml.getNode("printcs/commoncs");
				var advancedcs = faXml.getNode("printcs/advancedcs");
				//页边距
				if(this.option.margins == null) {
					this.option.margins = {};
				}
	        	this.option.margins["Top"] = commoncs.getNode("topdis").value;
				this.option.margins["Left"] = commoncs.getNode("leftdis").value;
				this.option.margins["Right"] = commoncs.getNode("rightdis").value;
				this.option.margins["Bottom"] = commoncs.getNode("bottomdis").value;
				//纵向，横向时，宽高互换
				var landScape = commoncs.getNode("printorientation").value === "level";
				if(landScape) {
					this.psheight = parseInt(commoncs.getNode("pswidth").value, 10);
					this.pswidth = parseInt(commoncs.getNode("psheight").value, 10);
				} else {
					this.psheight = parseInt(commoncs.getNode("psheight").value, 10);
					this.pswidth = parseInt(commoncs.getNode("pswidth").value, 10);
				}	
				//打印输出控制
				ofs = commoncs.getNode("celloverflowstrategy").value;
				if(!isNaN(ofs)) {
					ofs = parseInt(ofs, 10);
					if(ofs == 2) {
						ofs = 0
					} else if(ofs == 3){
					    ofs = 1;	
					} else {
						ofs = 2;
					}					
				} else {
					ofs = 2;
				}
				tableFillModel = ofs;
				var prcount = commoncs.getNode("printcount");
				if(prcount == null) {
					prcount = 1;
				} else {
					prcount = prcount.value;
				}
				//置底区域向上对齐.
				this.bottomfurl = commoncs.getNode("bottomfurl");
				if(this.bottomfurl != null) {
					this.bottomfurl = this.bottomfurl.value;
				}
				//生成参数
				setParams = {
					//打印纸张
					"Paper":{
						"Type":commoncs.getNode("custompagesize").value === "true" ? 
								    "Custom" : commoncs.getNode("sheettype").value,
						"Width":this.pswidth,
						"Height":this.psheight
					},
					//页边距
					"Margins":this.option.margins,
					//打印页码
					"PageCount":prcount,
					//是否横向
					"LandScape":landScape,
					//缩放比例
					"ZoomValue":params.zoomvalue || commoncs.getNode("zoomvalue").value,
					//文档名称
					"DocumentName":params.documentName || params.DocumentName,
					//文本输出模式
					"TextModel":tableFillModel,
					//是否显示系统打印窗口
					"ShowSysWin":params.spwinShow,
					"Copies":params.Copies,
					//置底区域向上对齐
					"BottomFurl":this.bottomfurl
				};
				var czv = commoncs.getNode("zoomvalue").value;
				if(czv != null && czv !== "") {
					cZoomValue = parseInt(czv, 10)/100;
				}
				//打印空白行
				var psr = commoncs.getNode("printspacerow");
				if(psr != null) {
					this.option.printEmptyRow = this.getBooleanValue(psr.value, false);
				} else {
					this.option.printEmptyRow = false;
				}
				//卡片式打印
				this.option.printcard = commoncs.getNode("printcard");
				if(this.option.printcard != null) {
					this.option.printcard = this.option.printcard.value;
				}			
				//打印页码选项
				var header = ["", "", ""];
				var footer = ["", "", ""];
				var sh = "0";
				var sf = "0"
				var showpagenum = commoncs.getNode("showpagenum");
				if(showpagenum == null) {
					showpagenum = true;
				} else {
					showpagenum = showpagenum.value;
				}
				if(showpagenum == "true") {
					var pnp  = commoncs.getNode("pagenumposition").value;
					var tst = commoncs.getNode("pagenumalign");
					if(tst == null) {
						tst == "center";
					} else {
					    tst = tst.value;
					}
					var ts = commoncs.getNode("pagenumstyle").value;
					if(pnp == "1") {
						sh = "1";
						if(tst == "left") {
							header[0] = ts;
						} else if(tst == "right") {
							header[2] = ts;
						} else {
							header[1] = ts;
						}
					} else {
						sf = "1";
						if(tst == "left") {
							footer[0] = ts;
						} else if(tst == "right") {
							footer[2] = ts;
						} else {
							footer[1] = ts;
						}
					}
				}				
				//每页打印记录选项				
				var cmp = commoncs.getNode("custompprc").value;
				if(cmp != null && cmp == "true") {
				    //this.setRecordAPage(commoncs.getNode("perpagerecordcount").value);
				    this.option.rowCountPerPage = commoncs.getNode("perpagerecordcount").value;
				} else {
					this.option.rowCountPerPage = 0;
				}
				if(this.option.rowCountPerPage != null && this.option.rowCountPerPage > 0) {
				    this.setRecordAPage(this.option.rowCountPerPage);
				}
				//套打处理
                var fp = advancedcs.getNode("formulaprint").value; 
                this.option.formulaPrint = this.getBooleanValue(fp,false);				
				//页眉页脚
                var pht = commoncs.getNode("pagehead")
                if(pht != null) {
                	pht = pht.value;
                }                
				if(pht != null || sh == "1") {
					if(sh == "0") {
						header = ["", "", ""];
					}
					if(pht != null) {
					    header[1] = pht + header[1];
					}		
					var headOption = {
						               "isShowLine":false,
						               "LineAlignment":"Near"
						              }
				    this.setHeader(header, headOption);
				}	
				var pft = commoncs.getNode("pagefoot");
				if(pft != null) {
					pft = pft.value;
				}				
				if(pft != null || sf == "1") {
					if(sf == "0") {
						footer = ["", "", ""];
					}
					if(pft != null) {
					    footer[1] = pft + footer[1];
					}
					var footOption = {
						               "isShowLine":false,
						               "LineAlignment":"Near"
						              }
				    this.setFooter(footer, footOption);
				}
				
				//高级属性
                //附加打印选项
				//图片打印选项
                //特殊效果打印选择
				this.option.extrabzprint = this.getBooleanValue(advancedcs.getNode("extrabzprint").value, false);
				this.option.extrabzprinttype = advancedcs.getNode("extrabzprinttype").value;
				this.option.extrabzprintposition = advancedcs.getNode("extrabzprintposition").value;	
				//打印logo
				var plogo = advancedcs.getNode("dologoprint");
				if(plogo != null) {
				    this.option.printLogo = this.getBooleanValue(plogo.value, false);
				}
				var plogopsn = advancedcs.getNode("logoprintposition");
				if(plogopsn != null) {
					this.option.printLogoPosition = plogopsn.value;					
				}
				//主从表打印选项
                var pa = advancedcs.getNode("printallmstable").value;
                if(pa != null && pa == "true") {
                	this.setPrintAllTable(true);
                } else {
                	this.setPrintAllTable(false);
                }
                //从表下一页开始打印
                this.option.subTableNextPage = advancedcs.getNode("secondtabledetach").value == "1";
                //子表记录分组打印
                if(advancedcs.getNode("groupGrid") != undefined ){ // 曾经的历史记录没有 “子表记录分组打印 groupGrid”属性，
                    this.option.subgroupGrid = advancedcs.getNode("groupGrid").value;
                    this.option.subgroupField =  advancedcs.getNode("groupField");
                    if(this.option.subgroupField != null) {
                    	this.option.subgroupField = this.option.subgroupField.value;
                    }
                }
                //多子表打印选项
                this.option.subGridOnOnePage = this.getBooleanValue(advancedcs.getNode("printmoretableonepage").value, false);
                //审批信息打印选项
                var psi = advancedcs.getNode("printspinfo");
                if(psi != null) {
                    this.option.printSpInfo = this.getBooleanValue(psi.value, false);
                    psi = null;
                }                
                //审批信息打印方式  1.单独打印, 2.一体打印
                var spt = advancedcs.getNode("spPrint");
                if(spt != null) {
                    this.option.spPrintType = spt.value;
                }                
                if(params.notPrint != true) {
                	var mdlXml = advancedcs.getNode("modelXml");
                	if(mdlXml != null) {
		                var faPage = mdlXml.getNode("Page");
		                if(faPage != null) {
		                	mdlXml.delNode("Page", true);
		                	this.addPageNode(faPage);
		                	this.option.hasModelPage = true;		                	
		                	var nwf = faPage.getAttrib("NoWorkFlow");
		                	this.option.noWorkFlow = this.getBooleanValue(nwf, this.option.noWorkFlow);
		                	this.xmlDoc.dataField = faXml.dataField;	                	
		                	this.xmlDoc.dataFields = faXml.dataFields;
		                	faXml.dataField = {};
		                	faXml.dataFields = [];
		                }
		                faPage = null;
		                var Watermark = mdlXml.getNode("WaterMark");
		                if(Watermark != null) {
			                var preview = Watermark.getAttrib("Preview");
			                if(preview === "true") {
			                	preview = true;
			                } else {
			                	preview = false;
			                }
			                if(preview) {
			                	this.ReportNode.setAttrib("PreviewWatermark", true);
			                }
			                mdlXml.delNode("WaterMark", true);
			                this.addWatermarkNode(Watermark);
		                }
                	}
	                mdlXml = null;	                
                }
                //单据子表打印选项
				//faXml.setEmpty();
				faXml = null;
				//custompagesize 是否自定义纸张
	        } else {
	        	//当前格式时，要重新判断一下流程是否有设置
	        	this.option.noWorkFlow = true;
	        	if(this.option.control != null && this.option.control.getWindow != null 
	        			&& this.option.control.getWindow().getControl != null) {
					this.option.noWorkFlow = $("#workflowSequenseNode",this.option.control.getWindow().getControl()).length <= 0;
				}
				//宽度、高度
				if(this.option.level) {
					this.pswidth = params.PaperWidth || params.paperWidth || 297;
				    this.psheight = params.PaperHeight || params.paperHeight || 210;
				} else {
				    this.pswidth = params.PaperWidth || params.paperWidth || 210;
				    this.psheight = params.PaperHeight || params.paperHeight || 297;
				}
				//如果指定gridid的话，就只打一个表
				this.printAllTable = (this.option.gridid == null || !this.option.gridid instanceof Array);
				this.option.margins = params.margins || params.Margins || {"Top":8, "Left":8, "Bottom":8, "Right":8};
				
				//生成参数
				setParams = {
					//打印纸张
					"Paper":{
						"Type":params.PaperType || params.paperType || "A4",
						"Width":this.pswidth,
						"Height":this.psheight
					},
					//页边距
					"Margins":this.option.margins,
					//打印页码
					"PageCount":"ALL",
					//是否横向
					"LandScape":params.level == true || params.Level == true || params.LandScape == true || params.landScape == true || this.option.level == true,
					//缩放比例
					"ZoomValue":params.zoomvalue || params.zoomValue || params.ZoomValue,
					//文档名称
					"DocumentName":params.documentName || params.DocumentName,
					//文本输出模式
					"TextModel":params.TextModel || params.textModel || 2,
					//是否显示系统打印窗口
					"ShowSysWin":params.spwinShow == true || params.SpwinShow == true,
					"Copies":params.Copies
				};
				var czv = params.zoomvalue || params.zoomValue || params.ZoomValue;
				if(czv != null && czv !== "") {
					cZoomValue = parseInt(czv, 10)/100;
				}
				var footer = ["", this._i18n.qzz.perPage, ""]; 
				var footOption = {
						          "isShowLine":false,
						          "LineAlignment":"Near"
						         }
				this.setFooter(footer, footOption);
			}
	        this.option.zoomValue = cZoomValue;
	        
	        //初始化页面设置
			this.setPageSettings(setParams, true);
		},
		//打开页面
		openUrlOnIFrame:function(url, formatid, modelOnly, callBack) {
			var frame = $("#ecpPrintScheme" + formatid);
	        var newFormat = false;
	        if(frame.length == 0 
	        		|| frame.attr("src") !== url 
	        		    || frame[0].contentWindow == null 
	        		        || frame[0].contentWindow.$ == null) {
	        	if(frame.length > 0) {
	        		var pfDiv = frame.parent();
	        		frame.remove();
	        		pfDiv.remove();
	        	}
	        	frame = $("<iframe id='ecpPrintScheme"+formatid+"' width='"+$("body").width()+"px' height='"+$("body").height()+"px'></iframe>");
	            var div = $("<div id='ecpPrintSchemeDiv"+formatid+"' style='position:absolute;top:1px;left:1px;overflow:hidden;width:1px;height:1px;z-index:10000;'></div>");
	            div.append(frame);
	            $("body").append(div);
		        frame.attr("src", url);
		        var _this = this;
		        var loadFinish = false;
		        if(frame[0].attachEvent) {
		        	frame[0].attachEvent("onload", function() {
		        		loadFinish = true;
		        		_this.logInfo("frame load finish!!!");
		        	});
		        } else {
		        	frame[0].onload = function(){
		        		loadFinish = true;
		        		_this.logInfo("frame load finish!!!");
		        	}
		        }
		        var win = frame[0].contentWindow;
		        newFormat = true;
		        //等待页面加载完成。
		        var times = 0;
		        var grids, grid, tabs;
		        
		        var sh = setInterval(function() {
		        	_this.logInfo("wait for loading printStyle!");
		        	times ++;
		        	if(typeof win.$ === "function") {
	        			var query = $;
	        			var element = undefined;
	        			if(newFormat) {
	        			    query = win.$;
	        			    //win = undefined;					        			    
	        			} else {
	        				element = win.element;
	        			}	
						//判断是不是2.0的格式
	        			if(query.ecp == null || query.ecp.getUI == null) {
	        				clearInterval(sh);
	        				_this.utils.notify(_this._i18n.qzz.notSupportVersionTreeStyle);
	        				if(typeof callBack == "function") {
		        				callBack(false);
		        			}
	        				return;
	        			}
		        		if(tabs == null || tabs.length <= 0) {
			        		tabs = query("[ecpclass='ecp.ui.layout.TabPanel']");
					        if(tabs != null && tabs.length > 0) {
						        var tabsUI = query.ecp.getUI(tabs);
							    if(tabsUI != null) {
							    	var len = tabsUI.length();
							    	var i;
							    	for(i = 1; i < len; i++) {
							    		tabsUI.nextTab();
							    	}
							    	tabsUI.select(tabsUI.getTitle(0));
							    }
						    }
						}
				        
		        		var hasFinish = true;
		        		if(grids == null || grids == null) {
		        		    grids = query("table[dataField][inputer]:not([id$='_frozen'])");
		        		}
		        		var len = grids.length;
		        		for(var i = 0; i < len; i++) {
	        		    	grid = query(grids[i]);
	        		    	var ecpclass = grid.attr("ecpclass");
	        		    	if(ecpclass == null || ecpclass === "") {
	        		    	//if(grid.attr("render") != "true" && grid.attr("ecpclass") == null) {
	        		    		hasFinish = false;
	        		    		break;
	        		    	}				        		    	
	        		    }
		        		
		        		//添加流程判断是否已加载完成判断
		        		if(modelOnly !== true && hasFinish) {
			        		var wf = query("#workflowSequenseNode");
			        		if(wf.length > 0) {
			        			var wftab = wf.find("table");
			        			if(wftab.length == 0) {
			        				hasFinish = false;
			        			} else if(wftab[0].rows.length == 0) {
									hasFinish = false;
								}
			        		}
		        		}
		        		
		        		//页面加载标志
		        		var $body = query("body");
		        		//查看属性.
		        		if(window.console) {
		        			window.console.info("======>" + $body.attr("pageLoaded"));
		        		}
		        		if($body.attr("pageLoaded") != null && $body.attr("pageLoaded") !== "true" 
		        			&& $body.attr("pageLoaded") !== true) {
		        			hasFinish = false;
		        		}
		        		
		        		if(hasFinish && loadFinish) {
                            clearInterval(sh);
                            _this.logInfo("frame load finish1!!!");
		        			if(typeof callBack == "function") {
		        				callBack(query, element)
		        			}
						}
		        	}
		        	if(times >= 60) {
		        		clearInterval(sh);
		        		_this.logInfo("frame load finish2!!!");
		        		if(typeof callBack == "function") {
		        			callBack($);
		        		}
		        	}
		        }, 2500); 
		        url = null;
		        return;
	    	} else {
	    		var win = frame[0].contentWindow;
	    		var query = $;
				query = win.$;
				//判断是不是2.0的格式
				if(query.ecp == null || query.ecp.getUI == null) {
    				this.utils.notify(this._i18n.qzz.notSupportVersionTreeStyle);
    				if(typeof callBack == "function") {
    					callBack(false);
    				}
    				return;
    			}
				win = undefined;
				if(typeof callBack == "function") {
					callBack(query, undefined);
				}
	    	}
		},
        initBaseModel:function(query, element, id, headTop, marginLeft) {
        	//base data
            //打印状态
        	var curElement = null;
            if(typeof id === "string") {
            	if(this.option.allTableIds[id] == this.option.hasPrint) {
					return 0;
				}
            	curElement = query(id, element);
            } else {
            	curElement = $(id);   
            	id = id.id;
            }
            var mt = curElement;
            var po = curElement.attr("printOption");
            if(po != null && po !== "") {
			    po = JSON.parse(po);	
            }
            if(curElement.length > 0 && (curElement[0].tagName == "DIV" || curElement[0].tagName == "P")) {
				var divRY = curElement.attr("relativey");
	            var txt = curElement.find("div[name=divgrouptitle]");
	            var cAlign = "left";
	            var isDivs = txt.length;
	            if(txt.length == 0) {
	            	if(curElement[0].tagName == "DIV" && id !== "") {
	            		var cid = id;
	            		if(typeof cid == "string" && cid.indexOf("#") < 0) {
	            			cid = "#" + cid;
	            		}
		            	txt = query(cid, curElement);
	            	} else if(curElement[0].childNodes.length == 1 && 
	            			curElement[0].childNodes[0].nodeName == "#text" && curElement.text() !== ""
	            				|| curElement[0].tagName == "P") {
	            		txt = curElement;
	            	}
		            //右边浮动的时候， 把顶点坐标向上移。
		            if(txt.css("float") != null && txt.css("float").toUpperCase() == "RIGHT") {
		            	cAlign = "right";
		            }	
		            if(txt.length > 0) {
		                isDivs = 1;
		            }
	            }
	            var titleHead = 0;
	            var txtNode = null;
	            if(isDivs == 1) {
	            	titleHead = 20;
	            	//设置标题
	            	var strAry = txt.text().split(/\n/);
	            	var len = strAry.length;     	
	            	var lefts = marginLeft;
	            	var stxt = txt.text().replace(/<[Bb][Rr](\/?)| /g, "");
	        		var tw = txt.width();
	        		if(txt[0].tagName == "P") {
	        			tw = tw + stxt.length * 1.2
	        		}
	            	var cindex = 0;
	            	//右对齐的时候处理
	        		if(cAlign == "right") {
	        			cindex --;
	        			lefts = this.maxWidth - tw;
	        		}
	        		var fontSize = txt.css("fontSize").replace("px", "");
	        		fontSize = parseInt(fontSize, 10) - 3;
        			var isBold = "" ;
        			var txtFont = txt.css("font");
	        		if(txtFont != undefined){
	        		 isBold = txtFont.indexOf("bold") >= 0;
	        		}
	        		
	        		var fontName = "";
					var top = 0;
	        		var tpo = txt.attr("printOption");
					var lock = "";
					var color = "#000000";
					var height = titleHead * len;
					if(tpo != null && tpo !== "") {
						tpo = JSON.parse(tpo);	
					} else {
						tpo = po;
					}
					if(tpo != null) {
						fontSize = this._getPrintOption(tpo, ["fontSize","FontSize"], fontSize);
						fontName = this._getPrintOption(tpo, ["fontName","FontName"], fontName);
						color = this._getPrintOption(tpo, ["color","Color"], color);
						top = this._getPrintOption(tpo, ["top","Top"], top);
						lefts = this._getPrintOption(tpo, ["left","Left"], lefts);
						tw = this._getPrintOption(tpo, ["width","Width"], tw);						
						lock = this._getPrintOption(tpo, ["lock","Lock"], lock);
						cAlign = this._getPrintOption(tpo, ["align","Align"], cAlign);
						height = this._getPrintOption(tpo, ["height","Height"], height);	
					}
	        		
	        		//添加标题显示
	        		var textOption = {"top":top,
						              "left":lefts,
						              "width":tw,
						              "height":height,
						              "fontSize":fontSize,
									  "Color":color,
									  "fontName":fontName,
						              "align":cAlign,
						              "lineAlign":"Center",
									  "Lock":lock,
						              "id":(this.option.curTableId !== id)?id:undefined,
						              "B":isBold
						             };
		    		txtNode = this.addText(stxt,textOption);	 
	            	if(cAlign == "right") {
	        			len --;
	        		}
	        		//计算高度
	            	titleHead = len * titleHead;
	            }
	            mt = curElement.children("table");	
            }
			//处理直接是表格的情况
			if(mt.length == 0) {
				mt = curElement;
				if(mt.length > 0 && mt[0].tagName !== "TABLE") {
					mt = [];
				}
			}
			var baseHeight = 0;
			if(mt != null && mt.length > 0) {
				var mtab = mt[0];				
				var cls = $(mtab).attr("class");
			    if(divRY != null) {
			        if($(mtab).attr("relativey") == null) {
			        	$(mtab).attr("relativey", divRY);
			        }
			    }
				//过滤掉，一些不需要打印的表格
				if(cls == "ui-jqgrid-htable" || cls == "dbContainer" || mtab.hasPrint == this.option.hasPrintState) {
					return titleHead;
				}
				var params = {
						"id":id,
						"maxColWidth":this.maxWidth,
						"hasBorder":this.option.hasBorder,
						"table":mtab,
						"query":query
					};
				if(po != null && (po.optionEnable == true || po.optionEnable === "true")) {
					$.extend(true, params, po);
				}
				var tabNode = this.addHTMLTable(params);
				//打印状态
				mtab.hasPrint = this.option.hasPrintState;
				//打印状态
				this.option.allTableIds[id] = this.option.hasPrint;
				if(tabNode != null) {
				    baseHeight = mtab.offsetHeight;
				}
				txtNode = null;
			}
			return baseHeight + titleHead;
        },    
        /**
         * 添加表格模板
         */
		initGridModel : function(dataGrid) {
			var p = dataGrid.control[0].p;
			//表格是否已打印过
			if(this.option.allTableIds[p.id] == this.option.hasPrint) {
			    //返回高度
				return 0;
			}
			//获取相对位置
			var rly = 5;
			if(dataGrid.getOption().relativeY != null) {
				rly = dataGrid.getOption().relativeY;
			}
			var fontSize = 9;
			if(dataGrid.getOption().fontSize != null && dataGrid.getOption().fontSize !== "") {
				fontSize = dataGrid.getOption().fontSize;
			}
			//打印标题
			var title = "";
			var tabDiv = dataGrid.getControl().parents("DIV[ID^='gbox']");
			if(tabDiv.length > 0) {
				var tls = tabDiv[0].parentNode.attributes.title;
				if(tls != null) {
					title = tls.nodeValue;
				} else {
					var divtitle = tabDiv.parent().find("div[name=divgrouptitle]");
					if(divtitle.length > 0) {
						title = divtitle.text();
					}
				}
			}
			if(title != null && title !== "") {				
			    //设置标题表格
			    var tabCapNode = this.addTable({"top":0, "left":0, "id":"title_" + p.id});
			    var rowCapNode = this.addRow(tabCapNode);
			    this.addCell(rowCapNode, title, 
			    		{"colSpan":1,"rowSpan":1,"fontSize":fontSize,"align":"Left","lineAlign":"Center"});
			    this.setNoBorder(tabCapNode, "true");
			    this.setCellWidths(tabCapNode, "400");
			    this.setFixColumn(tabCapNode, 0);
			    //设置相对位置
			    if(this.option.curTableId != ""){
			    tabCapNode.setAttrib({"RelativeY":"true",
			           "RelativeTableID":this.option.curTableId,
			           "Y":rly});	
			    }
			    dataGrid.getOption().relativeY = 5;
			    //缓存当前ID
			    this.option.curTableId = "title_" + p.id;
			    txtNode = null;
			}
			var adm = this.addGridModel(dataGrid);
			
			this.option.curTableId = p.id;
			//打印状态
			this.option.allTableIds[p.id] = this.option.hasPrint;
			p = null;
			return adm;
        },
        /**
         * 激活所有tab页签上的表格
         */
        _activeAllTab:function(query, element, callBack) {
        	if(this.getPrintAllTable()) {
	        	var tabs = query("[ecpclass='ecp.ui.layout.TabPanel']", element);
				if(tabs.length > 0) {
				    var tabsUI = query.ecp.getUI(tabs);
				    if(tabsUI != null) {
				    	var len = tabsUI.length();
				    	var i;
				    	for(i = 1; i < len; i++) {
				    		tabsUI.nextTab();
				    	}
				    	tabsUI.select(tabsUI.getTitle(0));
				    	var allGrids = query("table[dataField][inputer]:not([id$='_frozen'])", element);	
				    	var _this = this;
				    	var times = 0;
				    	var sh = setInterval(function() {
				        	_this.logInfo("wait for loading TabPanel's grid!");
				        	times ++;	        	
				        	var hasFinish = true;
				        	var len = allGrids.length;
		        		    for(var i = 0; i < len; i++) {
		        		    	var grid = query(allGrids[i]); 
		        		    	if(grid.attr("render") != "true" && grid.attr("ecpclass") == null) {
		        		    		hasFinish = false;
		        		    		break;
		        		    	}				        		    	
		        		    }
			        		if(hasFinish) {
								clearInterval(sh);
								if(typeof(callBack) == "function") {
									callBack.apply(_this);
								}
							}		
				        	
				        	if(times >= 10) {
				        		clearInterval(sh);
								if(typeof(callBack) == "function") {
									callBack.apply(_this);
								}
				        	}
				        }, 1000);
				    }
				} else {
					if(typeof(callBack) == "function") {
						callBack.apply(this);
					}
				}
        	} else {
        		if(typeof(callBack) == "function") {
					callBack.apply(this);
				}
        	}				
        },
        /**
         * 初始化页面模板.
         */
		createModelFromPage : function(query, element, hasMainTable, callBack) {
			var spaceHeight = 10;
			var marginTop = 0;
			var marginLeft = 0;
			//获取指定标题信息
			this.option.baseTitle = this.option.baseTitle || [];
			this.option.baseTitle.push("#h1_title");
			this.option.baseTitle.push("#title");
			this.option.baseTitle.push("#dj_title");
			this.option.baseTitle.push("#queryTitle");
			//获取指定的抬头表格id
			this.option.baseHeader = this.option.baseHeader || [];
			this.option.baseHeader.push("#layout_tabledata");
			this.option.baseHeader.push("#layout_baseinfo");
			this.option.baseHeader.push("#layout_maintable");
			this.option.baseHeader.push(".billMain");
			this.option.baseHeader.push(".dj_baseinfo");
			//获取指定表尾的表格id
			this.option.baseFooter = this.option.baseFooter || [];
			this.option.baseFooter.push("#layout_footer");
			this.option.baseFooter.push("#layout_footer1");
			this.option.baseFooter.push("#layout_footer2");
			//处理指定打印的表格
			this.option.gridid = this.option.gridid || this.option.gridId;
			if(this.option.gridid != null) {
			    this.option.gridJson = {};
    			if(this.option.gridid instanceof Array) {				
	    			for(var i = 0, len = this.option.gridid.length; i < len; i++) {
		    			this.option.gridJson[this.option.gridid[i]] = this.option.gridid[i];
			    	}
    			} else {
	    			this.option.gridJson[this.option.gridid] = this.option.gridid;
    			}
			} else {
			    this.option.gridJson = null;
			}
			
			//处理打印特殊效果
			if(this.option.extrabzprint) {
				var imgUrl = "/grm/ecp/ecpjs/themes/images/extrabzprint_" + this.option.extrabzprinttype + ".gif";
				var imgLeft = marginLeft;
				var imgTop = marginTop;
				if(this.option.extrabzprintposition == "left") {
					imgTop = parseInt((this.maxHeight * this.option.zoomValue - 50)/2, 10);
				} else if(this.option.extrabzprintposition == "right") {
					imgLeft = this.maxWidth - 100;
					imgTop = parseInt((this.maxHeight * this.option.zoomValue - 50)/2, 10);
				} else if(this.option.extrabzprintposition == "center"){
					imgLeft = parseInt((this.maxWidth - 100)/2, 10);
					imgTop = parseInt((this.maxHeight * this.option.zoomValue - 50)/2, 10);
				} else if(this.option.extrabzprintposition == "bottom") {
					imgTop = this.maxHeight * this.option.zoomValue - 50;
					imgLeft = parseInt((this.maxWidth * this.option.zoomValue - 100)/2, 10);
				} else {
					imgLeft = parseInt((this.maxWidth * this.option.zoomValue - 100)/2, 10);
				}
				var extImg = this.addImage({"url":imgUrl, "top":imgTop, "left":imgLeft});
				extImg.setAttrib("Lock","absolute");
				extImg = null;
			}
			//打印logo
			if(this.option.printLogo) {
				var imgUrl = "/grm/ecp/ecpjs/themes/images/logo.jpg";
				var imgLeft = marginLeft;
				var imgTop = marginTop;
				var mgn = 50;
				if(this.option.printLogoPosition == "topleft") {
					//
				} else if(this.option.printLogoPosition == "topright") {
					imgLeft = this.maxWidth * this.option.zoomValue;
				} else if(this.option.printLogoPosition == "bottomleft") {
					imgTop = this.maxHeight * this.option.zoomValue + parseInt(this.option.margins.Top, 10) * this.pxPerMM;
				} else if(this.option.printLogoPosition == "bottomright") {
					imgLeft = this.maxWidth * this.option.zoomValue;
					imgTop = this.maxHeight * this.option.zoomValue + parseInt(this.option.margins.Top, 10) * this.pxPerMM;
				}
				var logoImg = this.addImage({"url":imgUrl, "top":imgTop, "left":imgLeft});
				logoImg.setAttrib("Lock","absolute");
				logoImg = null;
			}
			
			//添加可以指定title功能
			var headTop = 0;
			var top = 0, left = 0;
			var textOption = {};
			var titleText = "";
			var widths = this.maxWidth;
			var heights = 60, fontSize = 30, fontName=this._i18n.qzz.defFontFamily, color="#000000", lock="Top";
			if(typeof this.option.title == "string") {							
				titleText = $.ecp.utils.transFerredString(this.option.title.replace(/&|<>/g, ""));			    
			} else {
				var txt = query(this.option.baseTitle.join(","), element);
				if(txt != null && txt.length > 0) {
					fontSize = txt[0].style.fontSize || txt.css("fontSize");
					if(fontSize == null || fontSize === "") {
						fontSize = txt.find("font").attr("size");
					}
					if(fontSize == null || fontSize === "") {
						fontSize = 30;
					}
					if(typeof fontSize == "string") {
						fontSize = fontSize.replace("px","");
					}
					fontName = txt[0].style.fontName;
					color = txt[0].style.color;
					var heights = parseInt(txt.height(), 10) + 20;	
					top = txt.attr("relativey") || 0;
					var po = txt.attr("printOption");
					if(po != null && po !== "") {
					    po = JSON.parse(po);					
						fontSize = this._getPrintOption(po, ["fontSize","FontSize"], fontSize);
						fontName = this._getPrintOption(po, ["fontName","FontName"], fontName);
						color = this._getPrintOption(po, ["color","Color"], color);
						top = this._getPrintOption(po, ["top","Top"], top);
						left = this._getPrintOption(po, ["left","Left"], left);
						widths = this._getPrintOption(po, ["width","Width"], widths);
						heights = this._getPrintOption(po, ["Height","height"], heights);
						lock = this._getPrintOption(po, ["lock","Lock"], lock);
					}
					titleText = this.trim(this._getText(txt).replace(/&nbsp;|&|<>|([ ]+)/g, ""));
				}
				txt = null;
			}			
			//如果字符串不为空
			if(titleText != null && titleText !== "") {
				if(heights > 80) {
					heights = 80;
				}
				textOption = {"top":top,
			              "left":left,
			              "width":widths,
			              "height":heights,
			              "fontSize":fontSize,
			              "fontName":fontName,
			              "align":"Center",
			              "lineAlign":"Center",
			              "id":undefined,
			              "RelativeTableID":"1",
			              "Lock":lock,
			              "color":color
			             };
				//添加主标题	
				this.addText(titleText, textOption);
			}
			
			//添加html到尾部
			if(typeof this.option.footerHtml == "string") {
			    var htmlObj = query("#footerHtmlDiv", element);
			    if(htmlObj.length == 0) {
			        htmlObj = query("<div id='footerHtmlDiv'>" + this.option.footerHtml + "</div>");
			        query("body").append(htmlObj);
			    }
				var tabObj = htmlObj.find("table");
				//给每个table设置id
				for(var i = 0, tlen = tabObj.length; i < tlen; i++) {
					tabObj[i].id = "footerHtml" + i
					this.option.baseFooter.push("#footerHtml" + i);
				}
			}
			
			//设置表格打印状态对象
			this.option.curTableId = "";
			//没有表格跟在后面的text会被当作标题，每页显示，因此加一个空表格以示区别
			//var tabN = this.addTable(0,0,"tmpTables");
			//var rowN = this.addRow(tabN,1);
			//this.addCell(rowN, "", undefined, undefined, 11, "Left", "Center");
			//this.setCellWidths(tabN, "10");
			//this.setHeadCount(tabN, "0", 1);
		    //this.setNoBorder(tabN, true);
					    
		    this._activeAllTab(query, element, function(){
		    	//主表打印  循环打印抬头表格
		    	var sels = this.option.baseHeader.join(",") + ",[name=divgroup],[printOption]";
		    	//:not(tr):not(td):not([ecpclass='ecp.ui.datafield.Grid']):not([ecpclass='ecp.component.ui.qzz'])
				var groupDiv = query(sels, element);
				for(var i = 0, len = groupDiv.length; i < len; i++) {
					var tab = groupDiv[i];
					var $tab = $(tab);
					var gtab = $tab.children("[ecpclass='ecp.ui.datafield.Grid']:not([id$='_frozen']),[ecpclass='ecp.component.ui.qzz']," + sels);
					if(gtab.length == 0) {
						if(tab.tagName === "TR" || tab.tagName === "TD" 
							|| $tab.attr("ecpclass") === "ecp.ui.datafield.Grid"
								|| $tab.attr("ecpclass") === "ecp.component.ui.qzz") {
							continue;
						} else if(tab.tagName === "DIV") {
							var ctab = $(tab).children("table");
							if(ctab.length > 1) {
								for(var j = 0, jlen = ctab.length; j < jlen; j++) {
									this.initBaseModel(query, element, ctab[j], 0, 0)							
								}
							} else {
								this.initBaseModel(query, element, tab, 0, 0)
							}
						} else if(tab.tagName === "TABLE" || tab.tagName === "P") {
							this.initBaseModel(query, element, tab, 0, 0)
						} else if(tab.tagName === "HR") {
							//添加画线
						    var $tab = $(tab);
						    var po = $tab.attr("printOption");
						    if(po != null && po !== "") {
						    	po = JSON.parse(po);						        
						        this.addLine(po.text || po.Text, 
						        		{
						        		"style":po.style || po.Style, 
						        		"top":po.top || po.Top, 
						        		"left":po.left || po.Left, 
						        		"width":po.width || po.Width, 
						    		    "height":po.height || po.Height, 
						    		    "border":po.border || po.Border, 
						    		    "color":po.color || po.Color, 
						    		    "lock":po.lock || po.Lock, 
						    		    "id":po.id || po.Id});
						    }
						} 	
					}
				}
				//子表打印
				var dataGrids = query("[ecpclass='ecp.ui.datafield.Grid']:not([id$='_frozen']),[ecpclass='ecp.component.ui.qzz']", element);
		    	this.option.subGridIndex = 0;
		    	for(var g = 0; g < dataGrids.length; g++) {
		    		//隐藏的表格也不打印
		    		var hp = query(dataGrids[g]).closest("[hidepanel='true']");
					if(hp != null && hp.length > 0) {						
						continue;
					}
					hp = null;
		    		var grid = query.ecp.getUI(dataGrids[g]);
		    		if(this.getPrintAllTable()) {
			    		if(!this.option.printSpInfo && (grid == null || grid.getName() == "shenpiGridprocessExamineIdea")) {
			    			continue;
			    		}
			            this.initGridModel(grid);
		    		} else {
		    			if(this.option.gridJson != null) {
				    	    if(this.option.gridJson[grid.control[0].id] != null) {			    							    				
						    	this.initGridModel(grid);
				    		}
				    	} else {
				    		if(grid.control[0].id.indexOf("mainTable") >= 0) {
				    	        dataGrid = query.ecp.getUI(dataGrids[0]);
					    		this.initGridModel(grid);
				    		}
				    	}
		    		}
				} //for		
				//打印footer部份的表格
		    	for(var i = 0, len = this.option.baseFooter.length; i < len; i++) {
					this.initBaseModel(query, element, this.option.baseFooter[i], 0, 0);
				}
		    	var workflows = query("#workflowSequenseNode", element);
		    	if(workflows.length == 0) {
		    		this.setNoWorkFlow();
		    	} else {
		    		this.setWorkFlowWidth(workflows.width());
		    		var fs = workflows.css("fontSize").replace("px", "")
		    		if(fs != null && fs !== "") {
		    			this.setWorkFlowFontSize(fs);
		    		}
		    	}
		    	
				//二维码打印
		    	var barcodeImgs = query("[name='barcodeImg']", element);
			    if(barcodeImgs.length > 0) {
			    	//print barcode
			    	for(var i = 0, len = barcodeImgs.length; i < len; i++) {
						var imgUrl = barcodeImgs[i].src.replace(/&/g, "[AND]");
						if(this.option.barcode[imgUrl] != this.option.hasPrint) {
						    this.option.barcode[imgUrl] = this.option.hasPrint;
						    var imgNode = this.addImage({"url":imgUrl, "top":0, "left":this.maxWidth - 100 - 100 * i});
						    imgNode.setAttrib("Lock","absolute");
						    var pn = barcodeImgs[i].parentNode;
						    if(pn != null) {
						    	pn = pn.parentNode;
						    }
						    if(pn != null) {
						    	var df = $(pn).find("[datafield]").attr("datafield");
						    	var vn = imgNode.getNode("Value");
						    	if(df != null && vn != null) {
						    	    this.setDataField(vn, df);
						    	}
						    }
						}						
			    	}
			    }
				if(typeof(callBack) == "function") {
					callBack();
				}		    	
		    });
		},
		
		/**
		 * 获得表格数据
		 * @param dataGrid 表格控件对象
		 * @param firstGrid 是否为第一个表格
		 */
		_getInitGridData : function(dataGrid, firstGrid){
			var that = this,datas;
			var control = dataGrid.control[0];
			var printScheme = that.option;
			var gridParam = dataGrid.getGridParam();
			//主表走设置方案，子表通过扩展接口实现
			if(firstGrid && printScheme && printScheme.isPageRange != false){
				//打印或预览的数据来源处理
				var printRange;
				if(!this.isEmpty(printScheme)){
					var pageRange = printScheme.pageRange;
					if(!this.isEmpty(pageRange)){
						//为number类型表示“全部”和“当前页”
						if(typeof(pageRange) === "number"){
							if(pageRange === 1){
								//全部
								printRange = "all";
							}else{
								//当前页
								printRange = "current";
							}
						}else{
							//页码范围
							var pgRanges = pageRange.split("-");
							var prLen = pgRanges.length;
							//指定某页 a
							if(prLen === 1){
								pageRange = {begin:pageRange, end:pageRange}
							}else{
								var _begin = pgRanges[0];
								var _end = pgRanges[1];
								//从第1页到该页  -b
								if(_begin === "-"){
									pageRange = {begin:1, end:_end};
									
								}else if(pgRanges[1] === ""){
									//该页到最后一页 a-
									pageRange = {begin:_begin, end:-1};
								}else{
									//从开始页到结束页  a-b
									pageRange = {begin:_begin, end:_end};
								}
							}
						}
					}else{
						//默认全部
						printRange = "all";
					}
				}
				//打印所有数据
				if(printRange === "all"){
					if(dataGrid.isComponent != true && gridParam.virtual===true){//虚拟树表，获得数据模型的数据
						datas = dataGrid.__virtual.getViewData();
					}else{
						// 服务端分页 
						if($.isFunction(control.p.datatype) || gridParam.pager) {
							var findServerData = printScheme.findServerData;
							if(findServerData){
								if(typeof (findServerData) === "string") {
									findServerData = $.ecp.utils.evalPath(findServerData);
								}
								if($.isFunction(findServerData)){
									var psd = control.p.postData;
									if(dataGrid.isComponent && psd == null) {
										psd = {"_search":false,
												"currentPageNum":dataGrid.pageIndex,
												"pageSize":dataGrid.pageSize,
												"sidx":"","sord":"asc","nd":0}
									}
									pageRange = {begin:1, end:-1};
									datas = findServerData.call({}, dataGrid, psd, pageRange);
								}
							} else {
								//是否选择字段分组显示 isFieldGroups 字段 例如：t_xtywbillVO_summoney
								var isFieldGroups=this.option.subgroupField;

								if(isFieldGroups != null){ //用户选择了分组
									datas = that._getGridAllData(this.option.subgroupGrid);
							
									 var i,  stop, len = datas.length;
									 var valAry_re = [];
									 var valJson = {};
									 for (i=0; i<len; i++) {
										 var keyVal = datas[z][isFieldGroups];
										 if(keyVal == null || keyVal == undefined || keyVal === ""){
											 valAry_re.push(datas[i]);
										 } else {
											 if(valJson[keyVal] == undefined) {
											     valJson[keyVal] = [datas[i]];
											 } else {
												 valJson[keyVal].push(datas[i]);
											 }
										 }
									 }
									 for(var keyVal in valJson) {
										 valAry_re = valAry_re.concat(valJson[keyVal]);
									 }
									 datas =  valAry_re;
								}else{
									datas = that._getGridAllData(dataGrid);
								}
							
							}
						}else{
							datas = that._getGridAllData(dataGrid);
						}
					}
				}else if(printRange === "current"){
					//打印当前页数据
					if(gridParam.virtual===true){//虚拟树表，获得当前页数据
						datas = dataGrid.getCurrentView();
					}else{
						datas = that._getGridAllData(dataGrid,true);
					}
				}else{
					//打印指定页码范围的数据
				
					//服务端分页，数据通过findServerData回调函数获得（开发人员重写findServerData函数）
					if($.isFunction(control.p.datatype) || gridParam.pager){
						var findServerData = printScheme.findServerData;
						if(findServerData){
							if(typeof (findServerData) === "string") {
								findServerData = $.ecp.utils.evalPath(findServerData);
							}
							if($.isFunction(findServerData)){
								var psd = control.p.postData;
								if(dataGrid.isComponent && psd == null) {
									psd = {"_search":false,
											"currentPageNum":dataGrid.pageIndex,
											"pageSize":dataGrid.pageSize,
											"sidx":"","sord":"asc","nd":0}
								}
								datas = findServerData.call({}, dataGrid, psd, pageRange);
							}
						} else {
							datas = that._getGridAllData(dataGrid);
						}
					}else{
						//客户端分页
						datas = control.p.data;
						if(!this.isEmpty(datas) && !this.isEmpty(pageRange)){
							var begin = pageRange.begin;	//打印开始页数
							var end = pageRange.end;		//打印结束页数
							var postData = control.p.postData;//表格分页数据
							if(!this.isEmpty(postData)){
								var currentPage = postData.currentPageNum;//当前的页数
								var pageSize = postData.pageSize;//当前页记录数
								if(pageSize){
									var pageNum = Math.ceil(datas.length/pageSize);
									if(begin <= pageNum){
										var bgIndex = (begin - 1)*pageSize;
										if(bgIndex < 0){bgIndex = 1;}
										var endIndex;
										if(end >= pageNum || end === -1){
											endIndex = datas.length;
										}else{
											endIndex = end*pageSize;
										}
										//截取数组
										datas = datas.slice(bgIndex, endIndex);
									}else{
										datas = [];
									}
								}
							}
						}
					}
				}
			}else{
				//子表通过实现接口获得数据，如果获得的数据为空，则取全部数据
				var processSubTabData = printScheme.processSubTabData;
				if(processSubTabData){
					if(typeof (processSubTabData) === "string") {
						processSubTabData = $.ecp.utils.evalPath(processSubTabData);
					}
					if($.isFunction(processSubTabData)){
						datas = processSubTabData.call({}, dataGrid, control.p.postData);
					}
				}
				if(this.isEmpty(datas)){
					datas = that._getGridAllData(dataGrid);
				}
			}
			return datas;
		},
		initPrintGridPageData : function(datas, dataGrid, mcount, colModel, control, gridDataField){
			var _this = this;
			// datas = that._getGridAllData(dataGrid);
			 var dcount = datas ? datas.length : '';
				if(this.isEmpty(dcount)) {
					dcount = 0;
				}
				var sname = "", snAry, cData;
				var pKeyName = dataGrid.getPKeyName();
				var dateCol = {};
				dateCol = {};
				var gdfs = this.xmlDoc.getDataFields(gridDataField);
				var rowNode = gdfs.node;
				var colWidths = rowNode.pNode.getAttrib("TdWidths");
				if(colWidths == null || colWidths === "") {
					colWidths = []
				} else {
					colWidths = colWidths.split(/,/g);
				}
				var fontSize = 9;
				if(dataGrid.getOption().fontSize != null && dataGrid.getOption().fontSize !== "") {
					fontSize = dataGrid.getOption().fontSize;
				}
				var idata;
				for(var i = 0; i < dcount; i++) {
					idata = datas[i];
					var rowValue = {};
					var maxHeight = 24;
					var k = 0;
					for(var j = 0; j < mcount; j++) {
						if(colModel[j].hidden !== true) {
							sname = colModel[j].name;
							if( sname != null && sname !== "" && sname != "cb") {
								if(sname == "rn") {
									cData = i + 1;
								} else {
									snAry = sname.split(".");
									cData = idata[snAry[0]];
									if(cData != null) {
										var slen = snAry.length;
										if(slen > 1) {
											for(var k = 1; k < slen; k++) {
												cData = cData[snAry[k]]
											}
										}
										slen = null;										
										if(colModel[j].edittype == "checkbox"){
											var val = cData;
											cData = val == false || val == "false" ?  "" : "√";
										}else if(cData != null && cData !== "") {
											if(typeof control.formatter == "function") {
												cData =  control.formatter(idata[pKeyName], cData, j, idata);
												if(typeof(cData) == "string") {
												   //替换空格符,替换掉XML字符串
												   cData = cData.replace(/&nbsp(;)?/g, " ").replace(/&lt(;)?/g,"<").replace(/&gt(;)?/g,">").replace(/<([^<>]+)>/g,"");
												}
											} else if(dataGrid.isComponent) {
												cData = dataGrid.dataSet.getDisplay(sname, cData);
											}
											var formatStyle = colModel[j].formatStyle || colModel[j].formatstyle;
											if(formatStyle != null && formatStyle !== "") {
												cData = this._getFormatStr(cData, formatStyle);
											}
										}
								    } else {
								    	if(colModel[j].edittype != "checkbox") {
								    		if(typeof control.formatter == "function") {
										    	cData =  control.formatter(idata[pKeyName], cData, j, idata);
										    	if(cData != null && cData !== "") {
										    		//替换空格符,替换掉XML字符串
										    		cData = cData.replace(/&nbsp(;)?/g, " ").replace(/&lt(;)?/g,"<").replace(/&gt(;)?/g,">").replace(/<([^<>]+)>/g,"");
										    	}
									    	} else if(dataGrid.isComponent) {
									    		cData = dataGrid.dataSet.getDisplay(sname, cData);
									    	}
								    		var formatStyle = colModel[j].formatStyle || colModel[j].formatstyle;
											if(formatStyle != null && formatStyle !== "") {
												cData = this._getFormatStr(cData, formatStyle);
											}
								    	}
								    }
								} //else
								//计算最大行高
								if(colWidths.length > 0) {
									var fs = gdfs.cnode[sname];
									if(fs != null && fs.getAttrib("FontSize") != null && fs.getAttrib("FontSize") !== "") {
										fontSize = parseInt(fs.getAttrib("FontSize"), 10);
									}
									var curHeight = this._getTextHeight(cData, colWidths[k], fontSize);
									if(maxHeight < curHeight) {
										maxHeight = curHeight;
									}
								}
								rowValue[colModel[j].name] = cData;
								k++;
							} //if							
						}
					}
					_this.updateDataFields(gridDataField, rowValue);
					if(maxHeight > 0) {
						rowNode.setAttrib("Height", maxHeight);
					}
					if(i < dcount - 1) {
						rowNode = _this.appendDataFields(gridDataField);
					}
					rowValue = null;
				}
				//打印空白行部份
				if(_this.option.printEmptyRow) {
					if(dataGrid.isComponent) {
						//暂时不存在空白行
					} else {
						//ecp空白行
					    var rowCount = dataGrid.control[0].rows.length - 1;
					    if(dcount < rowCount) {
					    	for(var i = dcount; i < rowCount; i++) {
					    		rowValue = {};
					    		for(var j = 0; j < mcount; j++) {
					    			rowValue[colModel[j].name] = "";
					    		}
					    	   	_this.appendDataFields(gridDataField);
					    	   	_this.updateDataFields(gridDataField, rowValue);
					    	   	rowValue = null;
					    	}				    	
					    }
					}				    
				}
				//打印表格合计部份
				if(dataGrid.isComponent) {
					if(dataGrid.getOption().footerrow && !this.option._noAmount) {
						var rowValue = {};
						var maxHeight = 24;
						var k = 0;
						for(var j = 0; j < mcount; j++) {
							if(colModel[j].hidden !== true) {
								sname = colModel[j].name;
								if( sname != null && sname !== "" && sname != "cb") {
									if(sname == "rn") {
										cData = dataGrid.summaryText;
									} else {
										cData = dataGrid.dataSet.getSummary(sname);
										if(cData !== "") {
										    cData = dataGrid.dataSet.getDisplay(sname, cData);
										}
										var formatStyle = colModel[j].formatStyle || colModel[j].formatstyle;
										if(formatStyle != null && formatStyle !== "") {
											cData = this._getFormatStr(cData, formatStyle);
										}
									} // !rn
									rowValue[sname] = cData;
									k++;
									//计算最大行高
									if(colWidths.length > 0) {
										var fs = gdfs.cnode[sname];
										if(fs != null && fs.getAttrib("FontSize") != null && fs.getAttrib("FontSize") !== "") {
											fontSize = parseInt(fs.getAttrib("FontSize"), 10);
										}
										var curHeight = this._getTextHeight(cData, colWidths[k], fontSize);
										if(maxHeight < curHeight) {
											maxHeight = curHeight;
										}
									}
								}// sname
							}// hidden
						}// mcount;
						//添加到表格中
						rowNode = _this.appendDataFields(gridDataField);
						if(maxHeight > 0) {
							rowNode.setAttrib("Height", maxHeight);
						}
						_this.updateDataFields(gridDataField, rowValue);
					} //if footerrow
				} else {
					if(!this.option._noAmount && dataGrid.control[0].grid != null && dataGrid.control[0].grid.sDiv != null) {
						var table = $(dataGrid.control[0].grid.sDiv).find("table");
						var isShowTable= dataGrid.isHideGridFooterrow != true;
						if(isShowTable){
						if(table.length > 0) {
							table = table[0];
							//按行打印
							for(var i = 0, len = table.rows.length; i < len; i++) {
								var cr = table.rows[i];
								rowValue = {}; 
								var maxHeight = 24;
								var k = 0;
								for(var j = 0, clen = cr.cells.length; j < clen; j++) {
									if(colModel[j].hidden !== true && colModel[j].name != "cb") {
										//获取列字段，对应生成打印数据								   
										var cnAry = $(cr.cells[j]).attr("aria-describedby").replace(dataGrid.getControl()[0].p.id + "_", "");
										if(cnAry.length > 0) {
										     var inpt = $(cr.cells[j]).find("input");
											// var colName = cnAry[cnAry.length - 1];
											 if(inpt.length > 0) {
											     rowValue[cnAry] = inpt.val();
											 } else {								        
											     rowValue[cnAry] = _this.trim(_this._getText(cr.cells[j])); //F639613 by ywy
											 }	
											 cData = rowValue[cnAry];
										 }
										
										//计算最大行高
										if(colWidths.length > 0) {
											var fs = gdfs.cnode[sname];
											if(fs != null && fs.getAttrib("FontSize") != null && fs.getAttrib("FontSize") !== "") {
												fontSize = parseInt(fs.getAttrib("FontSize"), 10);
											}
											var curHeight = this._getTextHeight(cData, colWidths[k], fontSize);
											if(maxHeight < curHeight) {
												maxHeight = curHeight;
											}
										}
										k++;
									}
								}								
								//添加到表格中
								rowNode = _this.appendDataFields(gridDataField);
								if(maxHeight > 0) {
									rowNode.setAttrib("Height", maxHeight);
								}
								_this.updateDataFields(gridDataField, rowValue);
							}
						}
					}
				}
			}
			datas = null;
			p = null;
			colModel = null;
			mcount = null;
			datas = null;	
				
			sname = null;
			snAry = null;
			cData = null;	
			try {
			    return dcount;
			} finally {
				dcount = null;
			}			
		},
		
		
		/**
		 * 初始化打印表格数据
		 * @param query jquery对象
		 * @param element 容器
		 * @param dataGrid 表格控件对象
		 */
		initPrintGridData : function(query, element, dataGrid, firstGrid, callBack) {
			var that = this;
			//add Data;
			var dmdm = dataGrid.dataSource.getMetaDataModel();
		    var control = dataGrid.control[0];
		    var gridDataField = dataGrid.getName();
		    if(!this.hasDataFields(gridDataField)) {
		    	if(typeof callBack == "function") {
		    		callBack(0);
		    	}
		    	return;
		    }
		    var gridParam = dataGrid.getGridParam();
		    var colModel = gridParam.colModel;
		    var mcount = colModel.length;
		    
		    
		    //获得表格数据 20140929 
	
			 var _this = this;
			 var printRange; 
			 var pageRange = that.option.pageRange;
			 if(pageRange == null) {
				 pageRange = 1;
			 }
			//打印分页处理 为number类型表示“全部”和“当前页”
			if(typeof(pageRange)=== "number"){
				if(pageRange === 1){
					//全部
					printRange = "all";
				}else{
					//当前页
					printRange = "current";
				}
			}else{
				 //获取页码范围：如2-5
				var pgRanges = that.option.pageRange.split("-");
				 var prLen = pgRanges.length; //判断范围是否是 ： 2-或者 2-5  格式
				 if(prLen === 1){//该页到最后一页  2
					 printRange = {begin:pageRange, end:pageRange} 
				 }else{//从开始页到结束页 a-b
					 if(pgRanges[1] == ""){pgRanges[1] = -1;}; //  2-
					 printRange = {begin:pgRanges[0], end:pgRanges[1]};
				 }
			}
			//打印时。option中 range 指定了打当前页或者是全部或者是页码范围。会优先执行 打印范围
			if(that.option.range != null && that.option.range !== ""){
				printRange = that.option.range;
			}
			dataGrid.getRangeData(printRange, function(datas){
				 var rc = _this.initPrintGridPageData(datas, dataGrid, mcount, colModel, control, gridDataField);
				 if(typeof callBack == "function") {
					 callBack(rc);
				 }
			}); 			
			
		},
		/**
		 * 获得表格全部数据
		 * @param dataGrid 表格控件对象
		 * @param isCurren 是否为当前页
		 */
		_getGridAllData : function(dataGrid,isCurren){
			var datas = isCurren === true ? dataGrid.getPageData() : dataGrid.control[0].p.data;//获得当前页数据
			if(this.isEmpty(datas)){//处理服务端分页，只拿当前页数据
				var dm = dataGrid.getDataSource().getDataModel();
				if(dm != null) {
				    datas = dm.get(dataGrid.getName()).value();
				} else {
				    datas = [];
				}
				dm = null;
			}
			return datas;
		},
			/**
		 * 初始化抬头数据
		 * @param {Object} query jquery对象
		 * @param {Object} element iframe里面容器
		 * @param {Object} cardData卡片数据
		 */
		initPrintHeadData : function(query, element, cardData, cquery) {
			var that = this;
	        var dfv, dfs = this.getDataField();
			for(var df in dfs) {
				var cn = dfs[df];
				var dataField = df.replace(/\[[0-9]+\]./,"");
				//子表单屏打印的时候，用这分支
				if(dataField.indexOf(".") > 1 && this.option.control != null 
						&& this.option.control.prefix != null &&this.option.control.prefix !== "") {
				    dataField = dataField.replace(/[^.]+./, this.option.control.prefix);
				}
				//卡片式打印
				if(that.printcard === "true" && cardData){
					that.updateDataField(df, cardData[dataField]);
				}else{
					var qfv = query("[dataField='" + dataField + "']", element);
					dfv = query.ecp.getUI(qfv);
					if(dfv == null && cquery != null) {
						//如果主界面上没有这个数据，则从当前界面上找这个数据
						dfv = cquery.ecp.getUI(cquery("[dataField='" + dataField + "']", element));
					}
					if(dfv == null) {
						dfv = query.ecp.getUI(query("[dataField='"+df+"']", element));
					}
					if(dfv != null) {
						if(typeof dfv.getURL == "function") {
							var url = dfv.getURL().replace(/&/g, "[AND]");
							this.option.barcode[url] = this.option.hasPrint;
							var imgNode = cn.pNode;
							var ch = imgNode.getAttrib("Height");
							if(ch != null && ch !== "") {
							    url = url.replace(/height=([0-9]+)/g,"height=" + ch);
							}
							var cw = imgNode.getAttrib("Width");
							if(cw != null && cw !== "") {
							    url = url.replace(/width=([0-9]+)/g,"width=" + cw);
							}
							imgNode = null;
							url = this._transFullUrl(url);
							that.updateDataField(df, url);
						} else if(typeof dfv.getInputer === "function"
							&& typeof dfv.getInputer() == "object"
						    && dfv.getInputer().code === "ecp.ui.datafield.Checkbox") {
							var opt = dfv.getOption();
						    var ds = opt.data;
							var cs = dfv.getValues();
							var sps = "";
							if(opt.apeak) {
								sps = "\n";
							}
							var text = "";
							for(var i = 0, dlen = ds.length; i < dlen; i++) {
								var idata = ds[i];
								if(cs.indexOf(idata[opt.checkboxId]) >= 0) {
									text = "√ " + idata[opt.checkboxText];
								} else {
									text = "□ " + idata[opt.checkboxText];
								}
								if(i < dlen - 1) {
									text += sps
								}
								idata = null;
							}
							if(text !== "" && text != null) {
								that.updateDataField(df, text);
							}
							opt = null;
							ds = null;
							cs = null;
						} else {
							var ivl = dfv.getInput().val();
							if(typeof dfv.text == "function" && dfv.text() !== "") {
								ivl = dfv.text();
							}
							//直接传递时，没有生成billid
							if((ivl == null || ivl === "") && df === "billid") {
								if(this.option.billid != null) {
									ivl = this.option.billid;
								}
							}
							var fst = dfv.getInput().attr("formatStyle") || dfv.getInput().attr("formatstyle");
							var dffst = cn.getAttrib("formatStyle");
							if(dffst != null && dffst !== "") {
								fst = dffst;
							}
							if(fst != null && fst !== "") {
								ivl = this._getFormatStr(ivl, fst);
							}							
							var pn = cn.pNode;
							var oh = parseInt(pn.getAttrib("Height"), 10);
							var nh = this._getTextHeight(ivl, this._getTdWidth(cn), cn.getAttrib("FontSize"));
							if(nh > oh) {
								pn.setAttrib("Height", nh);
							}
							pn = null;
							fst = null;
						    that.updateDataField(df, ivl);
						}						
					} else if (qfv.length > 0) {
						var text = "";
						if(typeof qfv.value === "function") {
							text = qfv.value();
						}
						if((text == null || text === "") && typeof qfv.text === "function") {
							text = qfv.text();
						}
						if(text !== "" && text != null) {
							var pn = cn.pNode;
							var oh = parseInt(pn.getAttrib("Height"), 10);
							var nh = this._getTextHeight(ivl, this._getTdWidth(cn), cn.getAttrib("FontSize"));
							if(nh > oh) {
								pn.setAttrib("Height", nh);
							}
							pn = null;
							that.updateDataField(df, text);
						}
					} else {						
						if(typeof this.option.control.getDataModel == "function") {
							var text = this.option.control.getDataModel().get(df).value();
							if(text != null && text !== "") {
								var pn = cn.pNode;
								var oh = parseInt(pn.getAttrib("Height"), 10);
								var nh = this._getTextHeight(ivl, this._getTdWidth(cn), cn.getAttrib("FontSize"));
								if(nh > oh) {
									pn.setAttrib("Height", nh);
								}
								pn = null;
								that.updateDataField(df, text);
							}
						}
					}
					qfv = null;
				}
			}
			dfv = null;
			dfs = null;
			that = null;
		},
	
		_isEffect : function(param) {
			var filter = ["gid", "cb", "rn", "id"];
			if(typeof param === "string"){
				var id = param;
			} else {
				var id = param.attr("id")
			}
			var index = id.indexOf("_");
			if(index !== -1){
				id = id.substring(index + 1);
			}
			if(filter.indexOf(id) !== -1){
				try {
				    return false;
				} finally {
					filter = null;
				}
			}
			filter = null;
			return true;
		},
		//异步生成表格数据.
		_aysnInitGridData : function(query, element, dataGrids, curIndex, firstGrid, top, callBack) {
			if(curIndex < dataGrids.length) {
				var me = this;
				var dataGrid = query.ecp.getUI(dataGrids[curIndex]);
				if(dataGrid == null || this.option.gridJson != null && this.option.gridJson[dataGrid.control[0].id] == null) {					
	            	setTimeout(function(){me._aysnInitGridData(query, element, dataGrids, curIndex + 1, firstGrid, top, callBack), me = null}, 0);
	            } else {
	            	this.initPrintGridData(query, element, dataGrid, firstGrid, function(rc) {
	            		firstGrid = false;	            		
				        var tabN = me.getTableById(dataGrid.control[0].id);
				        if(tabN != null) {
				            //计算相对位置
					        if(curIndex <= 0) {
					        	top = me.getTop(tabN) - 10;
					        }
					        if(rc == 0) {
					        	rc = 1;
					        }
					        rc += parseInt(me.getHeadCount(tabN), 10) + 1;				        
					        top = top + rc * 22;
				        }
				        if(me.getPrintAllTable()) {				        
				            setTimeout(function(){me._aysnInitGridData(query, element, dataGrids, curIndex + 1, firstGrid, top, callBack), me = null}, 0);
				        } else if(typeof callBack == "function") {
				        	callBack(top);
				        }
	            	});			        
	            }
			} else {
				if(typeof callBack == "function") {
					callBack(top);
				}
			}
		},
		/**
		 * id名称转换，及加密处理.
		 */
		_transData:function(dataGrid, cData, formatStyle, rowid, idata, colIndex,fieldName) {
			var control = dataGrid.control[0];
			if(typeof control.formatter == "function") {
				cData =  control.formatter(rowid, cData, colIndex, idata);
				if(typeof(cData) == "string") {
				   //替换空格符,替换掉XML字符串
				   cData = cData.replace(/&nbsp(;)?/g, " ").replace(/&lt(;)?/g,"<").replace(/&gt(;)?/g,">").replace(/<([^<>]+)>/g,"");
				}
			} else if(dataGrid.isComponent) {
				var rn = dataGrid.dataSet.rootNode;
				var rd = rn.data;
				rn.level = 0;
				rn.data = idata;
				cData = dataGrid.dataSet.getDisplay(fieldName, cData, rn);
				rn.level = -1;
				rn.data = rd;
				rn = null;
				rd = null;
				//去掉所有连接
				if(typeof cData === "string") {
				    cData = cData.replace(/<[aA][^<>]*>|<\/[aA]>/g,"");
				}
			}
			if(formatStyle != null && formatStyle !== "") {
				cData = this._getFormatStr(cData, formatStyle);
			}
			return cData;
		},
		_asynMergeData:function(dataGrid, pKeyName, datas, sumDatas, colModel, mcount, dataFields, 
				cdataFields, rowNode, colWidths, fontSize, index, callBack) {
			//生成数据包.
			var _this = this;
			var ci = 0,i = 0;
			if(index != null) {
				i = index;
			}
			var dcount = datas.length;
			var idata = null,snAry = null;
			var sname = "",cData = "";
			for(; i < dcount && ci < 10; i++,ci++) {
				idata = datas[i];
				var rowValue = {};
				var maxHeight = 0;
				var k = 0;
				for(var j = 0; j < mcount; j++) {
					var ccm = colModel[j];	
					sname = ccm.name
					if(cdataFields[sname] != null) {
						if( sname != null && sname !== "" && sname != "cb") {
							cData = "";
							if(sname == "rn") {
								cData = i + 1;
							} else {
								snAry = sname.split(".");
								cData = idata[snAry[0]];
								var fsty = ccm.formatStyle || ccm.formatstyle;
								if(dataFields.cnode != null && dataFields.cnode[sname] != null) {
									var dfst = dataFields.cnode[sname].getAttrib("formatStyle");
									//获得格式中的fontSize
									fontSize = dataFields.cnode[sname].getAttrib("FontSize") || fontSize;
									if(dfst != null && dfst !== "") {
						    		    fsty = dfst;
									}
						    	}
								if(cData != null) {
									//获取具体的值
									var slen = snAry.length;
									if(slen > 1) {
										for(var k = 1; k < slen; k++) {
											cData = cData[snAry[k]]
										}
									}
									slen = null;
									//类型转换，
									if(ccm.edittype == "checkbox"){
										var val = cData;
										cData = val == false || val == "false" ?  "" : "√";
									}else if(cData != null && cData !== "") {
										cData = this._transData(dataGrid, cData, fsty, idata[pKeyName], idata, j,sname);
									}
							    } else if(ccm.edittype != "checkbox") {
							    	//为空的时候，也有可能被格式化成别的内容
							    	cData = this._transData(dataGrid, cData, fsty, idata[pKeyName], idata, j,sname);
							   	}
							} //else
							//计算最大行高
							if(colWidths.length > 0) {
								var curHeight = this._getTextHeight(cData, colWidths[k], fontSize);
								if(maxHeight < curHeight) {
									maxHeight = curHeight;
								}
							}
							rowValue[ccm.name] = cData;
							k++;
						} //if							
					}
				}
				_this.updateDataFields(dataFields, rowValue);
				if(maxHeight > 0) {
					if(maxHeight > 8 && maxHeight < 24) {
						maxHeight = 24;
					}
					rowNode.setAttrib("Height", maxHeight);
				}
				if(i < dcount - 1) {
					rowNode = _this.appendDataFields(dataFields);
				}
				rowValue = null;
			}
			if(i < dcount) {
				setTimeout(function(){
					_this._asynMergeData(dataGrid, pKeyName, datas, sumDatas, colModel, mcount, dataFields, 
							cdataFields, rowNode, colWidths, fontSize, i, callBack);
				},0);
			} else {
				//打印空白行部份
				if(_this.printEmptyRow) {
					if(dataGrid.isComponent) {
						//暂时不存在空白行
					} else {
						//ecp空白行
					    var rowCount = dataGrid.control[0].rows.length - 1;
					    if(dcount < rowCount) {
					    	for(var i = dcount; i < rowCount; i++) {
					    		rowValue = {};
					    		for(var j = 0; j < mcount; j++) {
					    			var ccm = colModel[j];
					    			if(ccm.hidden !== true && cdataFields[sname] != null) {
					    			    rowValue[ccm.name] = "";
					    			}
					    		}
					    	   	_this.appendDataFields(dataFields);
					    	   	_this.updateDataFields(dataFields, rowValue);
					    	   	rowValue = null;
					    	}				    	
					    }
					}				    
				}
				//打印合计行
				if(sumDatas.length > 0) {
					var res = {"&lt;":"<", "&gt;":">","&nbsp;":" "};
					for(var i = 0, len = sumDatas.length; i < len; i++) {
						idata = sumDatas[i];
						rowValue = {}; 
						var maxHeight = 0;
						var k = 0;
						for(var j = 0; j < mcount; j++) {
							var ccm = colModel[j];	
							sname = ccm.name;
							if(sname != null 
									&& sname !== "" && sname != "cb" && cdataFields[sname] != null) {
								cData = idata[sname];	
								if(typeof cData == "string") {								
									cData = cData.replace(/<([^<>]+)>|&([a-z]+)(;)?/g, function(key, $1, $2) {
							    	       var key = res[key];
							    	       if(key == null) {
							    	           key = "";
							    	       }
							    	       return key;
							    	});
								}
								rowValue[sname] = cData;
								//计算最大行高
								if(colWidths.length > 0) {
									var curHeight = this._getTextHeight(cData, colWidths[k], fontSize);
									if(maxHeight < curHeight) {
										maxHeight = curHeight;
									}
								}
								k++;	
							}
						}//for j
						//添加到表格中
						rowNode = null;
						var dfSum = "sum" + i;
						if(dataGrid.sumDataField != null) {
						    var df = dataGrid.sumDataField[dfSum];
						    if(df != null) {
						    	dataFields = df;
							    if(df.node != null) {
									rowNode = df.node;
								}
						    }
						}
						if(rowNode == null) {
						    rowNode = _this.appendDataFields(dataFields);
						}
						if(maxHeight > 0) {
							if(maxHeight > 8 && maxHeight < 24) {
								maxHeight = 24;
							}
							rowNode.setAttrib("Height", maxHeight);
						}
						_this.updateDataFields(dataFields, rowValue);	
					}//for i
				}//if sumDatas
				snAry = null;
				cData = null;
				if(typeof callBack === "function") {
					callBack();
				}//grid					
			}//else
		},
		/**
		 * 合并数据到模板上
		 */
		mergeDataToModel : function(datas, dataGrid, dataFields, callBack){
		    var _this = this;
		    var dcount = datas ? datas.length : '';
			if(this.isEmpty(dcount)) {
				dcount = 0;
			}
			
			var pKeyName = dataGrid.getPKeyName();
			//获得节点列表
			var rowNode = dataFields.node;
			var tabNode = rowNode.pNode;
			var cdataFields = dataFields.cnode;
			if(cdataFields == null) {
				return;
			}
			//获得各列宽
			var colWidths = tabNode.getAttrib("TdWidths");
			if(colWidths == null || colWidths === "") {
				colWidths = []
			} else {
				colWidths = colWidths.split(/,/g);
			}
			var fontSize = 9;
			if(dataGrid.getOption().fontSize != null && dataGrid.getOption().fontSize !== "") {
				fontSize = dataGrid.getOption().fontSize;
			}
		    var gridParam = dataGrid.getGridParam();
		    var colModel = $.extend([],gridParam.colModel);
		    if(dataGrid.isComponent) {
				if(dataGrid.getOption().rownumbers) {
					colModel.splice(0, 0, {"caption":this._i18n.qzz.index,"index":"rn","name":"rn", "width":60,"hidden":false,"colIndex":0});
				}
			}
		    gridParam = null;
		    var mcount = colModel.length;
			var idata, sname = "", snAry, cData;
			//获取合计行
			var sumDatas = [];
			//打印表格合计部份
			if(dataGrid.isComponent) {
				if(dataGrid.getOption().footerrow && !this._noAmount) {
					var rowValue = {};
					var sumCol = tabNode.getAttrib("Sum1");
					var sumJson = {};
					if(sumCol != null) {
						var sumAry = sumCol.split(",");
						for(var j = 0, slen = sumAry.length; j < slen; j = j + 2) {
							sumJson[sumAry[j]] = sumAry[j + 1];
						}
					}
					for(var j = 0; j < mcount; j++) {
						var ccm = colModel[j];
						sname = ccm.name;
						if(ccm.hidden !== true && cdataFields[sname] != null) {
							if( sname != null && sname !== "" && sname != "cb") {
								cData = "";
								if(sname == "rn") {
									if(sumJson[sname] !== "") {
										cData = sumJson[sname];
									} else {
									    cData = dataGrid.summaryText;
									}
								} else {
									cData = dataGrid.dataSet.getSummary(sname);
									if(typeof cData == "string" && cData !== "" && cData.indexOf(this._i18n.qzz.summary) < 0) {
									    cData = dataGrid.dataSet.getDisplay(sname, cData);
									}
									if(cData === "" && sumJson[sname] !== "") {
										cData = sumJson[sname];
										if(cData == null) {
											cData = "";
										}
									}
//									var formatStyle = ccm.formatStyle || ccm.formatstyle;
//									if(formatStyle != null && formatStyle !== "") {
//										cData = this._getFormatStr(cData, formatStyle);
//									}
								} // !rn
								rowValue[sname] = cData;
							}// sname
						}// hidden
					}// mcount;
					sumJson = null;
					sumDatas.push(rowValue);
				} //if footerrow
			} else {
				if(!this.option._noAmount && dataGrid.control[0].grid != null && dataGrid.control[0].grid.sDiv != null) {
					var table = $(dataGrid.control[0].grid.sDiv).find("table");
					var isShowTable= dataGrid.isHideGridFooterrow != true;
					if(isShowTable){
						if(table.length > 0) {
							table = table[0];
							//按行打印
							for(var i = 0, len = table.rows.length; i < len; i++) {
								var cr = table.rows[i];
								rowValue = {};
								//解析原合计内容.
								var sumCol = tabNode.getAttrib("Sum" + (i + 1));
								var sumJson = {};
								if(sumCol != null) {
									var sumAry = sumCol.split(",");
									for(var j = 0, slen = sumAry.length; j < slen; j = j + 2) {
										sumJson[sumAry[j]] = sumAry[j + 1];
									}
								}
								for(var j = 0, clen = cr.cells.length; j < clen; j++) {
									cData = "";
									var ccell = cr.cells[j];
									//获取列字段，对应生成打印数据								   
									var sname = $(ccell).attr("aria-describedby").replace(dataGrid.getControl()[0].p.id + "_", "");
									if(sname.length > 0 && sname != "cb" 
										&& cdataFields[sname] != null) {
								     	var inpt = $(ccell).find("input");
									 	if(inpt.length > 0) {
									 		cData = inpt.val();
									 	} else {								        
									 		cData = _this.trim(_this._getText(ccell));
									 	}
								 	}
									if(cData === "" && sumJson[sname] !== "") {
										cData = sumJson[sname];
										if(cData == null) {
											cData = "";
										}
									}
									rowValue[sname] = cData;										
										
								}		
								sumJson = null;
								sumDatas.push(rowValue);
							}
						}
					}
				}
			}
			if(typeof this.option.formatFunc == "function") {
				this.option.formatFunc(datas, sumDatas, this.option.printRange);
			}
			this._asynMergeData(dataGrid, pKeyName, datas, sumDatas, colModel, mcount, dataFields, 
					cdataFields, rowNode, colWidths, fontSize, 0, callBack);
			datas = null;
			p = null;
			colModel = null;
			datas = null;
		    return dcount;	
		},
		
		setGridData : function(query, element, dataFields, dataFieldsAry,  curIndex, callBack) {
			var selector = "[dataField='"+dataFields.name+"'][ecpclass='ecp.ui.datafield.Grid']:not([id$='_frozen']),[dataField='"+dataFields.name+"'][ecpclass='ecp.component.ui.qzz']";
			var gridTables = query(selector, element);
			var dataGrid = null;
			var len = gridTables.length;
			if(len == 1) {
				dataGrid = query.ecp.getUI(gridTables[0]);				
			} else {
				for(var i = 0; i < len; i++) {
					var gridTable = gridTables[i];
					var $gridTable = $(gridTable);
					if((this.option.gridJson == null || this.option.gridJson != null && this.option.gridJson[gridTable.id] != null) && 
							$gridTable.attr("hasPrint") != true) {
						dataGrid = query.ecp.getUI(gridTable);
						var gkl = {};
						var cmd = dataGrid.getOption().colModel;
						for(var j = 0, clen = cmd.length; j < clen; j++) {							
							gkl[cmd[j].name] = 1;
						}
						var isCur = true;
						for(var ckey in dataFields.cnode) {
							if(ckey != "rn" && ckey != "cb" && gkl[ckey] != 1) {
								isCur = false;
								break;
							}
						}
						if(isCur) {
							$gridTable.attr("hasPrint", true);
							break;
						}
						gkl = null;
						cmd = null;
					} 
					$gridTable = null;
					gridTable = null;
				}
			}
			gridTables = null;
			if(dataGrid != null) {				
				var that = this;
				var printRange; 
				var pageRange = that.option.pageRange;
				if(pageRange == null) {
					 pageRange = 1;
				}
				//打印分页处理 为number类型表示“全部”和“当前页”
				if(typeof(pageRange)=== "number"){
					if(pageRange === 1){
						//全部
						printRange = "all";
					}else{
						//当前页
						printRange = "current";
					}
				}else{
					//获取页码范围：如2-5
					var pgRanges = that.option.pageRange.split("-");
					var prLen = pgRanges.length; //判断范围是否是 ： 2-或者 2-5  格式
					if(prLen === 1){//该页到最后一页  2
					     printRange = {begin:pageRange, end:pageRange} 
					}else{//从开始页到结束页 a-b
						 if(pgRanges[1] == ""){pgRanges[1] = -1;}; //  2-
						 printRange = {begin:pgRanges[0], end:pgRanges[1]};
					}
				}
				//打印时。option中 range 指定了打当前页或者是全部或者是页码范围。会优先执行 打印范围
				if(that.option.range != null && that.option.range !== ""){
					printRange = that.option.range;
				}
				var sumDf = {};
				var cdfNode = dataFields.node.pNode;
				var sumIndex = 0;
				for(var i = curIndex + 1, len = dataFieldsAry.length; i < len; i++) {
					var cdf = dataFieldsAry[i];
					if(cdfNode == cdf.node.pNode) {
						sumDf["sum" + sumIndex] = cdf;
						sumIndex ++;
					}
				}
				dataGrid.sumDataField = sumDf;
				dataGrid.getRangeData(printRange, function(datas){
					 that.printRange = printRange;
					 that.mergeDataToModel(datas, dataGrid, dataFields, function(){
						 dataGrid = null;
						 if(typeof callBack == "function") {
							 callBack(curIndex + sumIndex);
						 }
					 });
				}); 
			} else if(typeof callBack === "function"){
				callBack(curIndex);
			}
		},
		
		_setFmtWorkFlowData : function(callBack,query,element) {
			//生成岗位流程信息,单据特殊，在生成模板的时候，还没有的内容
			if(this.option.noWorkFlow !== true) {
				var wfss = null;
				if(this.option.hasFmid) {
					wfss = $("#workflowSequenseNode");
				} else {
				    wfss = query("#workflowSequenseNode", element);
				}
				var wftab = wfss.children("table");
				var dataAry = [];
				var fontSize = wfss.css("fontSize");
				if(fontSize != null && fontSize !== "") {
					fontSize = fontSize.replace("px", "");
				} else {
					fontSize = 12;
				}
				var pageNode = this.xmlDoc.getNode("Report/Page");
				var fs = pageNode.getAttrib("WorkFlowFontSize");
				if(fs != null && fs !== "") {
					fontSize = fs;
				}
        		fontSize = parseInt(fontSize, 10) - 3;
				if(wftab.length > 0) {	
						
					if(this.option.control != null 
							&& (typeof this.option.control.getMetaDataModel === "function"
								&& typeof this.option.control.getContext === "function" 
									|| this.option.classId != null && this.option.typeId != null)) {
						var classId = this.option.classId, 
						    typeId = this.option.typeId;
						if(this.option.control != null && this.option.control.getMetaDataModel != null) {
						    var ct = this.option.control.getMetaDataModel();
						    classId = ct.getClassId();
						    typeId = ct.getTypeId();
						};
						var ctx = null;
						if(this.option.control != null && this.option.control.getContext != null) {
							ctx = this.option.control.getContext();
						} else {
							ctx = null;
						}
						var that = this;
						this._getWorkFlowInfo(ctx, classId, 
								typeId, this.option.gid, "post", function(dataList){
							if(dataList == null) {
								dataList = [];
							}
							if(dataList.length > 0) {
								var cd = [];
								for(var i = 0, dlen = dataList.length; i < dlen; i++) {
									if(i%3 == 0 && i > 0) {
										dataAry.push(cd);
										cd = [];
										cd.push(dataList[i]);
									} else {
										cd.push(dataList[i]);
									}
								}
								dataAry.push(cd);
								cd = null;
								that.addArrayTable(dataAry, fontSize, 8, 0, false, null, [220,220,220]);
								pageNode = null;
								if(typeof callBack == "function") {
									callBack();
								}
							} else {
								wfmt = wftab[0];
								var colWidths = [];
								for(var i = 0, len = wfmt.rows.length; i < len; i++) {
									var row = wfmt.rows[i];
									var cd = [];
									for(var j = 0, clen = row.cells.length; j < clen; j++) {
										var txt = that._getText(row.cells[j]);
										cd.push(txt);
										if(colWidths[j] == null) {
											colWidths[j] = 100;
										}
										var sw = that._getTextWidth(txt, fontSize);
										if(colWidths[j] < sw) {
											colWidths[j] = sw;
										}
									}
									dataAry.push(cd);
								}
								that.addArrayTable(dataAry, fontSize, 8, 0, false, true, colWidths);
								pageNode = null;
								if(typeof callBack == "function") {
									callBack();
								}
							}								
						});
					} else {
						pageNode = null;
						if(typeof callBack == "function") {
							callBack();
						}
					}
				} else {
					pageNode = null;
					if(typeof callBack == "function") {
						callBack();
					}
				}		
			} else {
				if(typeof callBack == "function") {
					callBack();
				}
			}
		},
		
		_setWorkFlowData : function(flowType, callBack) {
			var _this = this;
			if(this.option.control.getMetaDataModel == null 
					&& (this.option.classId == null || this.option.typeId == null)){
				if(typeof callBack == "function") {
					callBack();
				}
				return;
			}
			var classId = this.option.classId, 
			    typeId = this.option.typeId;
			if(this.option.control.getMetaDataModel != null) {
			    var ct = this.option.control.getMetaDataModel();
			    classId = ct.getClassId();
			    typeId = ct.getTypeId();
			};
			var ctx = null;
			if(this.option.control.getContext != null) {
				ctx = this.option.control.getContext();
			} else {
				ctx = null;
			}			
			this._getWorkFlowInfo(ctx, classId, 
			    typeId, this.option.gid, flowType, function(dataList){
				if(dataList == null) {
					dataList = [];
				}
				if(flowType == "post") {
				    if(dataList.length > 0) {				    	
						var td = _this.xmlDoc.dataField["_postflow"];
						var tab = td.pNode.pNode;
						var k = 0;
						for(var i = 0, rlen = tab.nodeAry.length; i < rlen; i++) {
							var tr = tab.nodeAry[i];
							for(var j = 0, clen = tr.nodeAry.length; j < clen; j++) {
								td = tr.nodeAry[j];
								td.value = dataList[k++];
							}
							tr = null;
						}
						td = null;
						tab = null;
				    }
				} else {
					var wfdf = _this.xmlDoc.getDataFields("_workflow");					
					for(var i = 0,dlen = dataList.length; i < dlen; i++) {
						var cr = dataList[i];
						_this.updateDataFields(wfdf, {"number":i+1,"post":cr.postName,"unit":cr.departMentName,
							"time":$.ecp.utils.strToDate(cr.operatorTime, true, undefined, true),
							"user":cr.operatorUser, "context":cr.operatorOpinion});
					    if(i < dlen - 1) {
						    rowNode = _this.appendDataFields(wfdf);
					    }
					}
					wfdf = null;
				}
				if(typeof callBack == "function") {
					callBack();
				}
			});
			
		},
		
		_printWorkFlow:function(query, element, callBack) {
			var wfdf = this.xmlDoc.getDataFields("_workflow");
			var pfdf = this.xmlDoc.dataField["_postflow"];
			if(wfdf != null) {
				var _this = this;
				this._setWorkFlowData("work",function(){						
					if(pfdf != null) {
						_this._setWorkFlowData("post",function(){
							if(typeof callBack == "function") {
								callBack();
							}
						});
					} else {
						if(typeof callBack == "function") {
							callBack();
						}
					}						
				});
			} else if(pfdf != null){
				var _this = this;
				_this._setWorkFlowData("post",function(){
					if(typeof callBack == "function") {
						callBack();
					}
				});
			} else {
				this._setFmtWorkFlowData(callBack,query,element);
			}
			wfdf = null;
        },		
		/**
		 * 异步设置dataField值.
		 */
		_asynSetDataFields : function(query, element, dataFieldsAry, index, callBack) {
			if(index < dataFieldsAry.length) {
				var me = this;
				var dataFields = dataFieldsAry[index];
				if(dataFields == null) {					
	            	setTimeout(function(){me._asynSetDataFields(query, element, dataFieldsAry, index + 1, callBack), me = null}, 0);
	            } else {
	            	this.setGridData(query, element, dataFields, dataFieldsAry, index, function(curIndex) {
				        setTimeout(function(){me._asynSetDataFields(query, element, dataFieldsAry, curIndex + 1, callBack), me = null}, 0);
	            	});			        
	            }
			} else {
				this._printWorkFlow(query, element, callBack);
			}
		},
		_getWorkFlowInfo : function(context, classId, typeId, gid, flowType, callBack) {
			try {
				if(flowType == "post") {
			        $.ecp.workflow.utils.getWorkFlowData(classId, typeId, gid, callBack);
				} else {
				    $.ecp.workflow.utils.getWorkflowTrace(classId, typeId, gid, callBack);
				}
			} catch(e) {
				this.logInfo(this._i18n.qzz.flowIntErr + e.message);
				if(typeof callBack == "function") {
					callBack([]);
				}
			}
		 },
		/**
		 * 设置所有dataField的值.
		 */
		setDataFieldValue : function(query, element, callBack) {
			var ele;
			if(this.option.control != null && typeof this.option.control.getContext == "function") {
				ele = this.option.control.getContext().getContainer();
			}
			//dataField
			if(this.option.hasFmid && this.option.hasModelPage) {
				query = $;
				element = ele;
			}
			this.initPrintHeadData(query, element, false, $);
			var df = this.xmlDoc.dataFields;
			var dataFields = [];
			for(var i = 0, len = df.length; i < len; i++) {
				dataFields.push(df[i]);
			}
			df = null;
			if(dataFields.length > 0) {
				var me = this;
				this._asynSetDataFields(query, element, dataFields, 0, callBack);
			} else if(typeof callBack === "function") {
				//生成岗位流程信息,单据特殊，在生成模板的时候，还没有的内容
				//if(this.option.noWorkFlow !== true) {
				//    this.initBaseModel(query, element, "#workflowSequenseNode", 0, 0);
				//}
				this._printWorkFlow(query, element, callBack);
				//callBack();
			}
		},
		/**
		 * 初始化各字段数据
		 * @param {Object} query jquery对象
		 * @param {Object} element iframe里面容器对象
		 * @param {Array} dataGrids表格数组
		 * @param (Object) cardData 卡片数据 
		 */
		initDataField : function(query, element, dataGrids, cardData, callBack) {
			if(this.option.isBillPrint) {
				var ele = element;
				if(typeof this.option.control.getContext == "function") {
					ele = this.option.control.getContext().getContainer();
				}
			    this.initPrintHeadData($, ele, cardData, query);
			} else {
				this.initPrintHeadData(query, element, cardData);
			}
			//grid
			if(dataGrids != null) {
				var me = this;
				this._aysnInitGridData(query, element, dataGrids, 0, true, 0, function(top) {
					top += 10;
					//处理结束部份的文本数据打印
					for(var i = 0, len = me.baseFooter.length; i < len; i++) {
						var txtN = me.getTextById(me.baseFooter[i]);
						if(txtN != null && txtN.id == me.baseFooter[i]) {
							this.setTop(txtN, top);
							top += parseInt(txtN.getAttrib("Height"),10);
						}
					}
					if(typeof callBack == "function") {
						callBack();
					}
				});
			} 
		},
		/**
		 * 通过dataField填充数据到打印模板中
		 * <p>
		 * 	填充数据分为列表和卡片，列表打印列表或者卡片打印卡片则按照所见打印即可，而如果列表打印卡片则列表有几天记录打印卡片就有几个。<br>
		 *  卡片打印主要思路：用现有的xml对象创建一个新的xml对象，每遍历一条数据就给新xml对象增加相应节点，然后把新xml对象赋值给旧xml对象即可。
		 * </p>
		 * @ignore
		 * @param {Object} query 当前页面的query对象
		 * @param {Object} element iframe里面的容器
		 */
		_fillFromDataField : function(query, element, callBack){
			var that = this;
			var selector = "[ecpclass='ecp.ui.datafield.Grid']:not([id$='_frozen']),[ecpclass='ecp.component.ui.qzz']";
			//获取iframe里面的表格列表
			var gridAryFromIframe = query(selector, element);
			//卡片式打印（列表打印卡片）
			if(that.printcard === "true") {
				//查询该单据是列表还是卡片
				var url = window.location.search.substring(1),
					formatId = url && url.match(/formatid=([\w]*)/),
					foramtObj;
				if(this.notEmpty(formatId)){
					formatId = formatId[1];
					try{
						//服务端请求改有3.0模式
						var bindId ="com.ygsoft.ecp.component.ef.service.context.IViewFormatContext";
						var mothed = "getFormatByFormatId";
						var bindArray = [formatId];
						foramtObj = rs.RemoteService.doPost(bindId, mothed, bindArray);
					}catch(e){
						that.logInfo(this._i18n.qzz.queryErr.replace("{0}", formatId));
					}
				}
				//单据为卡片时直接打印
				if(!foramtObj || foramtObj.formatStyle == 1){
					//传入主页面的$符
		            that.initDataField($, element, gridAryFromIframe, undefined, callBack);
		            return;
				}
				//获取当前单据或页面的表格列表
    			var dataGrids = $(selector, that.getContainer()|| $("body"));
    			if($.type(dataGrids) !== "array"){
    				dataGrids = [dataGrids];
    			}
    			//获得初始化表格数据 
    			var newXmlDoc = new printXmlDoc();
				for(var i = 0, j = dataGrids.length; i < j; i++) {
					var dataGrid = $.ecp.getUI(dataGrids[i]);
					var curGridId = dataGrid.control[0].id;
					if(dataGrid == null || this.option.gridJson != null && this.option.gridJson[curGridId] == null) {
		            	continue;
		            }else{
	        			var datas = that._getInitGridData(dataGrid, true);
	        			var control = dataGrid.control[0];
	        			var colModel = control.p.colModel;
	        			var pkName = dataGrid.getPKeyName();
	        			if(this.isEmpty(datas)){break;}
	        			var firstCard = true;
	        			var xmlDoc = that.xmlDoc;
	        			//获取page节点下的所有子节点
	        			var allTables = xmlDoc.getNode("Report/Page/Table");
	        			var allTexts = xmlDoc.getNode("Report/Page/Text");
	        			var allImgs = xmlDoc.getNode("Report/Page/Img");
	        			if(!allTables && !allTexts && !allImgs){break;}
	        			//pageHeight为page下面的所有节点的总高度
	        			var tabIds = [], textIds = [], pageHeight = 0;
	        			if($.type(allTables) === "object"){allTables = [allTables];}
	        			if($.type(allTexts) === "object"){allTexts = [allTexts];}
	        			if($.type(allImgs) === "object"){allImgs = [allImgs];}
	        			//获取table节点的id和表格的高度
	        			if(allTables && allTables.length !== 0){
	        				for(var i=0,j=allTables.length; i<j; i++){
	        					var tabNode = allTables[i];
	        					//保存表格ID
	        					tabIds[i] = tabNode.getAttrib("ID");
	        					//计算高度
	        					var rtid = tabNode.getAttrib("RelationTableID");
	        					var trNodes = tabNode.getNodes()["Tr"]["array"];
	        					if(trNodes && trNodes.length !== 0){
	        						for(var n=0,m=trNodes.length; n<m; n++){
	        							var ph = trNodes[n].getAttrib("Height");
	    	        					ph = ph ? +ph : 0; 
	        							pageHeight += ph;
	        						}
	        					}
	        					//存在相对位置ID时把Y属性的值计算如总高度中
	        					if(rtid){
	        						var tabY = tabNode.getAttrib("Y");
	        						tabY = tabY ? +tabY : 0;
	        						pageHeight += tabY;
	        					}
	        				}
	        			}
	        			//获取text节点的Id和文本的高度
	        			if(allTexts && allTexts.length !== 0){
	        				for(var i=0,j=allTexts.length; i<j; i++){
	        					var textNode = allTexts[i];
	        					//缓存文本id
	        					textIds[i] = textNode.getAttrib("ID");
	        					//计算高度
	        					var rtid = textNode.getAttrib("RelationTableID"),textY=0;
	        					if(!rtid){
	        						textY = textNode.getAttrib("Y");
	        						textY = textY ? +textY : 0;
	        					}
	        					var ph = textNode.getAttrib("Height");
	        					ph = ph ? +ph : 0; 
	        					pageHeight += ph + textY;
	        				}
	        			}
	        			
	        			//遍历卡片
	        			for(var n=0,m=datas.length; n<m; n++){
	        				//处理数据的ID名称转换
	        				var newData = datas[n];
	        				if(colModel){
	        					for(var s=0,t=colModel.length; s<t; s++){
	        						var colm = colModel[s];
	        						var colNm = colm.name;
	        						if(colNm === "rn" || colNm === "cb" || colNm === "sr"){continue;}
	        						newData[colNm] = control.formatter(newData[pkName],$.ecp.utils.nvl(newData,colNm,""),s,newData)
	        					}
	        				}
	        				//给模板填充数据
				            that.initDataField($, element, gridAryFromIframe, newData);
				            if(firstCard){
				            	newXmlDoc.setXml(xmlDoc.toString(true));
		        				firstCard = false;
		        			}else{
		        				//组成新表格节点
		        				if(allTables && allTables.length !== 0){
		        					for(var i=0,j=allTables.length; i<j; i++){
		        						if(!allTables[i]){break;}
		        						var tabNode = $.extend(true,{},allTables[i]),
		        							rtid = tabNode.getAttrib("RelativeTableID"),
		        							nodeId = tabIds[i]+"_"+n,
		        							tabY = tabNode.getAttrib("Y");
		        						tabNode.setAttrib("ID", nodeId);
		        						if(rtid){
		        							tabNode.setAttrib("RelativeTableID", rtid+"_"+n);
		        						}else{
		        							tabY = tabY ? +tabY : 0;
		        							tabNode.setAttrib("Y", pageHeight*n + tabY + 10);
		        						}
		        						newXmlDoc.getNode("Report/Page").addNode(tabNode);
		        					}
		        				}
		        				//组成新文本节点
		        				if(allTexts && allTexts.length !== 0){
		        					for(var i=0,j=allTexts.length; i<j; i++){
		        						if(!allTexts[i]){break;}
		        						var textNode = $.extend(true,{},allTexts[i]),
		        							rtid = textNode.getAttrib("RelativeTableID");
		        						if(rtid){
		        							var nodeId = textIds[i]+"_"+n;
		        							textNode.setAttrib("ID", nodeId);
		        							textNode.setAttrib("RelativeTableID", rtid+"_"+n);
		        						}else{
		        							var textY = textNode.getAttrib("Y");
		        							textY = textY ? +textY : 0;
		        							textNode.setAttrib("Y", pageHeight*n + textY + 10);
		        						}
		        						newXmlDoc.getNode("Report/Page").addNode(textNode);
		        					}
		        				}
		        				//组成新二维码节点
		        				if(allImgs && allImgs.length !== 0){
		        					for(var i=0,j=allImgs.length; i<j; i++){
		        						if(!allImgs[i]){break;}
		        						var imgNode = $.extend(true,{},allImgs[i]),
	        								imgY = imgNode.getAttrib("Y");
	        							imgY = imgY ? +imgY : 0;
	        							imgNode.setAttrib("Y", pageHeight*n + imgY);
		        						newXmlDoc.getNode("Report/Page").addNode(imgNode);
		        					}
		        				}
		        			}
	        			}
	        			break;
		            } //grid
				}
				that.xmlDoc = newXmlDoc;
				if(typeof callBack == "function") {
					callBack();
				}
				newXmlDoc = null;
			}else{
				this.setDataFieldValue(query, element, callBack);	
			}
		},
		getCurFormatId : function(thisWin) {
			var curFmidAry = [];
		    var url = ""
			if(thisWin.getWindow != null) {
				var cw = thisWin.getWindow();
				if(cw.location != null) {
				    url = cw.location.href;
				} else if(cw.url != "undefined" && cw.url != null) {
					url = cw.url;
				}
			}
		    if(url != null && url !== "") {
		    	if(url.indexOf("EfNavigateServlet?_d=") > 0) {
		    		url = url.split("EfNavigateServlet?_d=")[1];
		    		url = des.decodeBase64(url);
		    	}
		    	curFmidAry = url.match(/format[iI]d=([\w]+)/);
		    }
		    if(curFmidAry != null && curFmidAry.length > 1) {
		    	return curFmidAry[1];
		    } else if(url != null && url.indexOf("gris.ywdj") > 0) {
		    	return "gris.ywdj";
		    } else {
		    	return "";
		    }
		},
		/**
		 * 获取打印模板.
		 * @params {json} params 参数对象
		 * @params
		 */
		getPrintModel:function(params, callBack) {
			//第一种情况，直接从打印方案中读取打印模板，
			//第二种情况，直接从格式中解析出来，
		},
		/**
		 * 设置打印数据.
		 */
		setPrintData:function(params, callBack) {
			
		},
		/**
		 * 执行打印
		 */
		doPrintData:function(params, callBack) {
			
		},
		/**
		 * 获得元数据模型 .
		 */
		getMetaDataModel:function(thisWin) {
		    var context = null;
			if(typeof thisWin.getContext === "function"){
			    context = thisWin.getContext();
			}
			var mdm = null;
			if(context != null && typeof context.getMetaDataModel === "function"){
			    mdm = context.getMetaDataModel();
			}
			return mdm;
		},
		/**
		 * 获得数据模型 .
		 */
		getDataModel:function(thisWin) {
		    var context = null;
			if(typeof thisWin.getContext === "function"){
			    context = thisWin.getContext();
			}
			var dm = null;
			if(context != null && typeof context.getDataModel === "function"){
			    dm = context.getDataModel();
			}
			return dm;
		},
		
	    /**
	     * 获得页面url.
	     */
		_getPageUrl:function(params, curFmid, typeId, classId) {
	    	 var url = "", fmid = "";	     
			//直接加载
			if(params.faVo != null  && params.faVo.printgs != "1" &&  params.faVo.printgs != null) {
			    var fmidAry = params.faVo.printgs.split("_");	
			    var reload = this.getBooleanValue(params.reload, false);
			    fmid = fmidAry[1];
			    if(fmidAry != null && fmidAry.length > 1 && fmidAry[1].length > 1
			    	&& (reload || fmidAry[1] !== curFmid)) {
			    	//服务端请求改有3.0模式
			    	var bindId ="com.ygsoft.ecp.component.ef.service.context.IViewFormatContext";
					var mothed = "findByPrimaryKeys";
					var bindArray = [[fmidAry[1]]];
					var curFmt = rs.RemoteService.doPost(bindId, mothed, bindArray);
				    if(curFmt != null && curFmt.length > 0) {
				        url = "/grm/ecp/EfNavigateServlet?formatid="+fmidAry[1]+"&typeId=" + typeId + "&classId=" + classId;
				        //添加gid
				        if(this.option.gid != null) {
				        	url += "&gid=" + this.option.gid;
				        }
				        //去除缓存
				        url += "&cacheState=0";
				        hasFormat = true;
				    }  else { //curFmt;
				    	this.utils.notify(this._i18n.qzz.noSchemeErr);
				    } 
				}   
			} else if(this.option.url != null && this.option.url !== "") {
			    url = this.option.url;
			}
			return {"url":url,"fmid":fmid};
		},
		//处理数据
		fillDataToModel:function(params, query, element, callBack) {
			if(params.modelOnly !== true) {
				//生成打印数据
				this._fillFromDataField(query, element, callBack);
			} else {
				//打印后事件
				if(typeof params.onAfterPrint == "function") {
					params.onAfterPrint();
			    }
				if(typeof(callBack) == "function") {
					callBack();
				}
			}
		},		
		/**
		 * 打印份数.
		 */
		setPrintCounts : function() {
			var option = this.printScheme || this.option;
			//设置打印份数.
		    try {
    			if(option.gid != null && option.gid !== 0) {
			    	var iservice = "com.ygsoft.ecp.app.operator.system.service.context.IXtdyfaContext";
			    	var mothed = "setPrintCounts";
			    	var bindArray = [option.classId, option.typeId, (option.gid || "") + "", option.yhdm];
			    	rs.RemoteService.doPost(iservice, mothed, bindArray);
			    }
		    } catch(e) {
		    	//
		    }	
		},
		/**
		 * 初始化数据.
		 */
		initData : function(params, callBack) {
	        this.option = params;
	        //增加直接传入打印xml字符串
	        if(typeof this.option.xmlStr == "string" && this.option.xmlStr !== "") {
	        	if(this.option.decode != false) {
	        		var me = this;
	        	    this.xmlDoc.setXml(this.option.xmlStr, function() {
	        		    //打印后事件
		        	    if(typeof me.option.onAfterPrint == "function") {
		        	    	me.option.onAfterPrint();
				        }
		        	    if(typeof(callBack) == "function") {
						    callBack();
					    }
	        	    });	        	
	        	} else {
	        		//打印后事件
	        	    if(typeof this.option.onAfterPrint == "function") {
	        		    this.option.onAfterPrint();
			        }
	        	    if(typeof(callBack) == "function") {
					    callBack();
				    }
	        	}
	        	return;
	        }
			var faId = 1;
			//获取横纵向打印属性
			this.option.level = this.getBooleanValue(this.option.level, false);
			if(typeof this.option.format == "function") {
				this.option.formatFunc = this.option.format;
			}
			//处理打印格式
			this.option.notPrint = this.getBooleanValue(this.option.notPrint, false);
		    if(this.option.faVo != null && this.option.faVo.printgs == null && this.option.formatId != null)  {
		    	this.option.faVo.printgs = "_" + this.option.formatId;
		    }
		    //是否显示打印窗口.
		    if(this.option.noSpwinShow) {
		    	this.option.spwinShow = !this.option.noSpwinShow;
		    } else {
		    	this.option.spwinShow = true;
		    }
		    //打印缩放
		    if(this.option.zoom || this.option.Zoom 
		    		|| this.option.zoomvalue || this.option.zoomValue || this.option.ZoomValue
		    		    || this.option.scale || this.option.Scale) {
		    	this.option.zoomvalue = this.option.zoom || this.option.Zoom 
		    	    || this.option.scale || this.option.Scale;
		    }
		    
		    if(this.option.margins != null || this.option.Margins) {
		    	this.option.margins = this.option.margins || this.option.Margins;
		    }
		    this.option.noAmount = this.getBooleanValue(this.option.noAmount, false);
		    this.option.Copies = this.option.pageCount || 1;
			//打印后事件
			var _this = this;
			//获得前台格式id, 参考模型
			if(this.option.control != null) {
				var curFmid = this.getCurFormatId(this.option.control);
				if(this.option.formatId != null && this.option.formatId != "1") {
					curFmid = "";
				}
				this.option.hasFmid = curFmid !== "";
			}
			//setting
			this.initScheme(this.option);
			//是否只是打印模板
			if(this.option.preview === true) {
				this.option.modelOnly = true;	
			}			
			//有模板，且前台是打开的单据
			if((this.option.hasFmid || this.option.modelOnly || this.option.data != null) && this.option.hasModelPage) {
				if(this.option.data != null) {
			    	if(typeof this.option.data == "string") {
			    		this.option.data = JSON.parse(this.option.data);
			    	}
			    	this.base(this.option, callBack);
			    	return;
			    }
				//填充打印数据
				this.fillDataToModel(params, query, element, callBack);
			} else {
				//增加读取classId, typeId
				var classId = this.option.classId;
				var typeId = this.option.typeId;
				if(classId == null && this.option.control != null) {
					var mdm = this.getMetaDataModel(this.option.control);
					if(mdm != null) {
					    classId = mdm.getClassId();
					    typeId = mdm.getTypeId();
					}
				}
				//获得打印的gid
			    if(this.option.control != null && this.option.control.primaryKey !=null){
				    var djYwid = this.option.control.getDataModel().get(this.option.control.primaryKey).value();
				    if(djYwid != null && djYwid >= 0) {
				    	this.option.gid = djYwid;
				    }
			    }
			    //model
			    this.option.allTableIds = {};
			    var hasFormat = false;
			    if(params != null) {
					//获得传入的方案，或都URL，转换成单据格式url
					var obj = this._getPageUrl(params, curFmid, typeId, classId);
					if(obj.url != null && obj.url !== "") {
				        //打开打印格式页面
				        this.openUrlOnIFrame(obj.url, obj.fmid, (params.modelOnly == true || this.option.gid == null), 
				            function(query, element) {
								//添加打印失败分支
				            	if(query === false) {
							    	if(typeof callBack == "function") {
							    		callBack(false);
							    	}
				            	} else if(_this.option.hasModelPage) {
					            	//填充打印数据
					            	_this.fillDataToModel(params, query, element, callBack);
					            } else {
						        	//生成打印模板
						        	_this.createModelFromPage(query, element, (params.mainTable != null), function() {
						        		//填充打印数据
						        		_this.fillDataToModel(params, query, element, callBack);
						        	});	//createModelFromPage
								}
					        }); //openUrlOnIFrame
					} else {
						//生成打印模板
						this.createModelFromPage(query, element, (thisWin.mainTable != null), function() {
							//直接填充打印数据
							_this.fillDataToModel(params, query, element, callBack);
						});	
					} //openframe	
			    } else {
			    	//直接打印空白
			    	if(typeof callBack == "function") {
			    		callBack();
			    	}
			    }
			}//this.option.hasModelPage
		}		
	});
	/**
	 * 打印通用接口.
	 * @param {String} printType 打印类型 "Print"|"Preview"
	 * @param {Object} option 属性 
	 * @param {Object} option.control 页面控制器
	 * @param {String} option.classId 大类ID
	 * @param {String} option.typeId 小类ID                    , 
	 * @param {String} option.gridid 指定打印表格的id
	 * @param {String} option.formatId 指定格式id
	 * @param {Boolean} option.level 是否横向
	 * @param {String} option.xmlStr 打印模板
	 * @param {String} option.baseFooter 脚部id 
	 * @param {String} option.baseHeader 抬头id
	 * @param {String} option.baseTitle 标题 
	 * @param {Boolean} option.reload 重加载模板 
	 * @param {String} option.footerHtml 脚部的html嵌入的HTML字符串
	 * @param {String} option.findServerData 获取服务端数据接口，是个函数
	 * @param {Boolean} option.isPageRange 是否需要显示页面范围
	 * @param {Boolean} option.noSpwinShow 是否弹出选择打印方案窗口 （批量打印时会弹出多次选择方案窗口） true 表示不弹出
	 * @param {number} option.scale 缩放 100，90，80
	 * @param {String} option.range 打印当前窗口数据  例如：$.ecpPrint("Print", controller, {"gridid":gridid,"noSpwinShow":true,"range":"current"});
	 * @example 
	    //默认调用
	    $.ecpPrint("Preview", controllor);
	    //指定表格调用
	    $.ecpPrint("Print", controllor, {gridid:"gridid"});                  
	 */
	$.ecpPrint = function(printType, option, callBack) {
		if(printType !== "Preview" && printType !== "preview") {
			printType = "Print";
		} else {
			printType = "Preview";
		}
		//创建打印对象
		if($.ecpPrinter == null) {
			$.ecpPrinter = new qzz.print.ecpBean();
		} else {
			$.ecpPrinter.reset();
		}
	    //获取typeif, classid
		var _classId, _typeid, _gid;
		
		if(option != null) {
		    _classid = option.classId;
		    _typeid = option.typeId;
		    _gid = option.gid;
		}
		_yhdm = rs.DataContextUtil.getLoginContext().getUserId();
		if(option != null) {
			option.yhdm = _yhdm;
		}
		_unitCode = rs.DataContextUtil.getLoginContext().getLoginOrgId();

		//获取方案,typeid不为空， 或有方案，或有格式id
		if((option == null || option.modelOnly !== true) 
				//typeid 不为空
				&& (_typeid != null  
						//有方案id
						|| option != null && option.faVo != null  
						        //有格式id
								|| option != null &&  option.formatId != null) 
								    ) {
			var faVos = null;
		    var defId = "";
			var refId = "";
		    var datas = [];
		    var faJson = {};
		    var isCurrentFa;
		    //typeid 不为空的时候，读取方案列表
			if(_typeid != null) {
				try {				
					//!isNaN(_typeid) 为数字的时候，有可能是通用实体或业务单据，需要查询打印方案
					if(!isNaN(_typeid)) {
						 var bindId ="com.ygsoft.ecp.app.operator.system.service.context.IXtdyfaContext";
						 var mothed = "findEcpByTypeid";
						 var bindArray = [_typeid, _yhdm, _unitCode,"0","0"];
						 faVos = rs.RemoteService.doPost(bindId, mothed, bindArray);
					}
			    } catch(e) {
			    	faVos = null;
			    }
			    //方案列表不为空，则过滤掉不符合要求的方案,并获得默认方案
			    if(faVos != null && faVos.length > 0) {
			    	var postList = [];
				    try {
				    	var iservice = "com.ygsoft.ecp.app.mdm.service.auth.context.IEcpUserPostQueryContext";
				    	var mothed = "findUserPosts";
				    	var iprm = [_unitCode, _yhdm];
				    	postList = rs.RemoteService.doPost(iservice, mothed, iprm);
				    } catch(e) {
				    	postList = [];
				    }			          	
		        	var postJson = {};
		        	var postId;
		        	for(var i = 0, len = postList.length; i < len; i++) {
		        		postId = postList[i].postId
		        		postJson[postId] =  postId;
		        	}
		        	postId = null;
		        	var cfVo, cqxVo;
		        	var byhdm = _yhdm;
//		        	var curFmid = thisWin.printer.getCurFormatId(thisWin);
//		        	if(curFmid === "" && option.formatId !== "") {
					var curFmid = option.formatId;
//					}
                    //var curFmid = "";
		        	for(var i = 0, j = 0, len = faVos.length; i < len; i++) {
		        		//所有单位与当前单位
		        	    cfVo = faVos[i];
		        	    cqxVo = cfVo.dyfaqxVO;
		        	    var dygs = cfVo.dygs;
		        	    var yhdm = "0"; 
		        	    var postid = "0";
		        	    if(cqxVo != null) {
			        	    yhdm = cqxVo.yhdm || yhdm;
			        	    postid = cqxVo.postid || postid;
		        	    }
		        	    if(cfVo.tybz == 1){
		        	    	continue;
		        	    }
		        		if((dygs === "1" || option != null && option.formatId != null && cfVo.printgs.indexOf(option.formatId) > 0 
		        				|| curFmid !== "" && dygs.indexOf(curFmid) >= 0) 
		        			  && (postid == "0" || postJson[postid] == postid)
		        				//当前操作员时，需要处理 0 为所有操作员 1 为当前操作员
		        				&& (yhdm == "0"
		        					  //指定用户
		        					  || yhdm == byhdm
		        					     //当前操作员
		        					     || yhdm == "1" && cfVo.yhdm == byhdm)) {
					        		datas[j] = {
					        		   id: cfVo.gid,
					        		   text: cfVo.famc
					        		};
									if (option != null && option.formatId != null && cfVo.printgs.indexOf(option.formatId) > 0) {
										refId = cfVo.gid;
									} else if(option != null && option.formatId != null) {
										cfVo.printgs = "1_" + option.formatId;
									}
					        		faJson[cfVo.gid] = cfVo;
					        		if(cfVo.isdefault == "1") {	
					        			//设置了打印格式的优先
										if(dygs.indexOf(curFmid) >= 0) {
	                                        if(defId === "" && yhdm !== "0" && yhdm !== "1") {
					        				    //指定用户时，优先级最高，(非所有用户， 非当前用户时)
	    					        			defId = datas[j].id;	
					        			    } else if(defId === "" && postid !== "0") {
					        				    //否则，指定岗位时次之 （非所有岗位时）
					        				    defId = datas[j].id;
					        			    } else if(defId === "") {
					        				    //都不指定最后（所有岗位，所有用户）
					        				    defId = datas[j].id;
					        			    }
										} else {
											if(defId === "" && yhdm !== "0" && yhdm !== "1") {
												//指定用户时，优先级最高，(非所有用户， 非当前用户时)
												defId = datas[j].id;	
											} else if(defId === "" && postid !== "0") {
												//否则，指定岗位时次之 （非所有岗位时）
												defId = datas[j].id;
											} else if(defId === "") {
												//都不指定最后（所有岗位，所有用户）
												defId = datas[j].id;
											}
										}
					        		}
					        		j++;
		        		}//if
		        	}//for
		        	if(datas.length == 0){
		        		isCurrentFa = true;
		        		if(defId !== "") {
			        		faJson[defId] = {
			        		    printgs:"1"
			        		}
		        		}
		        	}
				} else {
					isCurrentFa = true;
				}
			} else {
				//只有faVo 和 formatid
			}
			var hideSelWin = option && (option.spwinShow == false || option.noSpwinShow == true);
			var docName = "";
			if(option != null) {
				docName = option.documentName || option.DocumentName || "";
				if(docName === "" && _classid != null && _classid !== "" && _typeid != null && _typeid !== "") {
					docName = _classid + "_" + _typeid;
				}
			}
		    //如果指定格式，则用指定的格式
		    option.modelOnly = false;
		    if(option != null && (option.faVo != null) || hideSelWin) {
	            var pgs = "1";
		    	var fv = {};
        		if(defId !== "") {
        			pgs = defId;
        			//则用默认的方案
        			fv = faJson[defId];
        		}
        		//如果传入faVo
        		if(option.faVo != null) {
        		    fv = option.faVo;
        		    pgs = fv.printgs;
        		}
        		//如果传入格式
        		if(option.formatId != null) {
        			
					if(refId !== "") {
						var cfv = faJson[refId];
						if(cfv != null) {
							fv = cfv;
							cfv = null;
						} else {
							pgs = _typeid + "_" + option.formatId;
        			        fv.printgs = pgs;
						}
					} else {
						pgs = _typeid + "_" + option.formatId;
        			    fv.printgs = pgs;
					}
        		}
        		//增加自定义布局参数传入.
    		    //gridid, level, xmlStr, baseFooter, baseHeader, baseTitle, reload, footerHtml
        		option.printScheme = defId || 1;
        		option.faVo = fv;
        		option.printgs = pgs;
        		option.pageCount = 1;
        		option.documentName = docName;
        		// "current" ; 不弹出 ，只打当前页
        		option.range = option.range != null?option.range:"";
        		$.ecpPrinter.printData(printType, option, callBack);
        	} else {
        		var tit,winWith,winHeight,isPageRange, inTab;
        		if(printType === "Preview"){
        			tit = $.ecpPrinter._i18n.qzz.selPrivewScheme;
        			inTab = "<table style=\"width:100%\"><tr style=\"height:40px;text-align:right;padding-right:3px;\"><td>"+$.ecpPrinter._i18n.qzz.privewScheme+"</td><td colspan=2><select id='ptScheme' style='width: 288px;' class='entitySelectPlace select2-default' ><option>请选择...</option></select></td></tr>" +
        			        "<tr style=\"height:34px;text-align:right;\"><td style=\"padding-right:3px;\">"+$.ecpPrinter._i18n.qzz.privewRang+"</td><td style=\"text-align:left;\"><input type=\"radio\" name=\"prg\" id=\"printRange1\" checked>&nbsp;"+$.ecpPrinter._i18n.qzz.all+"</td><td></td></tr>" +
        			        "<tr style=\"height:34px;\"><td></td><td><input type=\"radio\" name=\"prg\" id=\"printRange2\">&nbsp;"+$.ecpPrinter._i18n.qzz.curPage+"</td><td></td></tr>" +
        			        "<tr style=\"height:34px;\"><td></td><td><input type=\"radio\" name=\"prg\" id=\"printRange3\">&nbsp;"+$.ecpPrinter._i18n.qzz.pageRange+"</td><td><input type=\"text\" class=\"form-control\" id=\"pageSize\"  disabled style=\"width:118px;\"></td></tr>" +
        			        "<tr style=\"height:50px;\"><td colspan=3><table><tr><td style=\"padding-right:3px;width:80px;text-align:right;\">"+$.ecpPrinter._i18n.qzz.printCount+"</td><td><input type=\"text\" class=\"form-control\" id=\"printCount\" style=\"width:60px;\" value=\"1\"></td></tr></table></td></tr>" +
        			        "</table>"
        		}else{
        			tit = $.ecpPrinter._i18n.qzz.selPrintScheme;
        			var msSelList = "<select id=\"printMs\" class=\"form-control\" style=\"width:100%\">";
        			var printers = $.ecpPrinter.getPrinters();
        			var defPrinter = $.ecpPrinter.getDefPrinter();            		
            		
        			inTab = "<table style=\"width:100%\">" +
        			        "<tr><td style=\"width:80px;height:50px;text-align:right;padding-right:3px;\">"+$.ecpPrinter._i18n.qzz.printer+"</td><td colspan=2><select id='printMs' style='width: 288px;' class='entitySelectPlace select2-default' ><option>请选择...</option></select></td></tr>" +
        				    "<tr><td style=\"width:80px;height:40px;text-align:right;padding-right:3px;\">"+$.ecpPrinter._i18n.qzz.printScheme+"</td><td colspan=2><select id='ptScheme' style='width: 288px;' class='entitySelectPlace select2-default' ><option>请选择...</option></select></td></tr>" +
        			        "<tr id=\"r1\" style=\"height:34px;text-align:right;\"><td style=\"padding-right:3px;\">"+$.ecpPrinter._i18n.qzz.printRang+"</td><td style=\"text-align:left;\"><div name=\"prg\" id=\"printRange1\" checked>&nbsp;"+$.ecpPrinter._i18n.qzz.all+"<div></td><td></td></tr>" +
        			        "<tr id=\"r2\" style=\"height:34px;\"><td></td><td><div name=\"prg\" id=\"printRange2\">&nbsp;"+$.ecpPrinter._i18n.qzz.curPage+"</div></td><td></td></tr>" +
        			        "<tr id=\"r3\" style=\"height:34px;\"><td></td><td><div name=\"prg\" id=\"printRange3\">&nbsp;"+$.ecpPrinter._i18n.qzz.pageRange+"：</div></td><td><input type=\"text\" class=\"form-control\" id=\"pageSize\" disabled style=\"width:168px;\"></td></tr>" +
        			        "<tr style=\"height:50px;\"><td colspan=3><table><tr><td style=\"padding-right:3px;width:80px;text-align:right;\">"+$.ecpPrinter._i18n.qzz.printCount+"</td><td><input type=\"text\" class=\"form-control\" id=\"printCount\" style=\"width:60px;\" value=\"1\"></td></tr></table></td></tr>" +
        			        "</table>"
        		}
        		if(option && option.noSpwinShow) {
        		    option.spwinShow = false;
        		}
        		var pgs = "1";
        		if(defId !== "") {
        			pgs = defId;
        		}
        		//option.spwinShow 是否弹出选择打印方案窗口 （批量打印时会弹出多次选择方案窗口）
        		option.pageCount = 1;
        		option.pageRange = 1;
        		option.printScheme = pgs;
        		option.printgs = 1;		
        		option.documentName = docName;
				//判断是否存在页码范围
        		winWith = 344;
	    		isPageRange = !(option && option.isPageRange == false);
	    		winHeight = !isPageRange ? 140 : 250;
	    		if(printType === "Preview" || printType === "preview") {
	    			winHeight -= 60;
	    		}
	    		var zIndex = null;
	    		if(option != null) {
	    			zIndex = option.zIndex || null;
	    		}
	    		
	    		var $ess = $("#ecpSchemeDlg");
	    		$ess.remove();
	    		$ess = $("#ecpSchemeDlg");
	    		if($ess.length == 0) {
	    			var winDiv = $("<div id=\"ecpSchemeDlg\"></div>");
	    			$("BODY").append(winDiv);
	    		    var winStr =  
				    		"<div id=\"ecpSchemeSelect\" class=\"modal show\" tabindex=\"-1\" role=\"dialog\" aria-hidden=\"true\" data-backdrop=\"static\">\n" +
				    		"    <div class=\"modal-dialog\" style=\"width:400px;\">\n" + 
				    		"        <div class=\"modal-content\">\n" + 
				    		"            <div class=\"modal-header modal_header_bgblue\">\n" + 
				    		"                <button type=\"button\" class=\"close\" id=\"ptClose\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>\n" + 
				    		"                <h4 class=\"modal-title\" style=\"color:#428bca;\">"+tit+"</h4>\n" + 
				    		"            </div>\n" + 
				    		"            <div class=\"modal-body\">\n" + 
				    		inTab + 
				    		"            </div>\n" + 
				    		"            <div class=\"modal-footer\">\n" + 
				    		"               <div style=\"float:left;\"><span id=\"print_count\"></span></div>" +
				    		"               <button type=\"button\" class=\"btn btn-default\" id=\"ptCansel\" data-dismiss=\"modal\">"+$.ecpPrinter._i18n.qzz.cancel+"</button>" + 
				    		"<button type=\"button\" class=\"btn btn-primary\" id=\"ptOk\" data-dismiss=\"modal\">"+$.ecpPrinter._i18n.qzz.ok+"</button>\n" + 
				    		"            </div>\n" + 
				    		"        </div>\n" + 
				    		"    </div>\n" + 
				    		"</div>";
				     winDiv.html(winStr);
				     //打印机列表
				     var printMs, $printMs = $("#printMs");
				     if($printMs.length > 0) {
				    	 var op = {
				             idField: 'id',
				             textField: 'text',
				             data :　printers
				         }
				         //渲染通用下拉控件
				         printMs = $printMs.comboBox(op);
				    	 if(defPrinter != null && defPrinter !== "") {
				    	     printMs.value(defPrinter);
				    	 }
				     }
				     var op = {
			             idField: 'id',
			             textField: 'text',
			             data :　datas
			         }
				     //打印方案列表.
				     var scheme = $("#ptScheme").comboBox(op);
				     if(defId != null && defId !== "") {
				         scheme.value(defId);
				     }
				     
				     var pr1 = $("#printRange1").qzzcheckbox({type:"radio",fontSize:14});
				     pr1.setCheck(true);
				     var pr2 = $("#printRange2").qzzcheckbox({type:"radio",fontSize:14});
				     var pr3 = $("#printRange3").qzzcheckbox({type:"radio",fontSize:14});
				     pr3.bind("onClick", function(state) {
					    if(state === true) {
		    				$("#pageSize").removeAttr("disabled");
		    			} else {
		    				$("#pageSize").attr("disabled",true);
		    			}
				     });
				     
				     $("#ptCansel").click(function(){
	                	if(typeof callBack == "function") {
				    		callBack(false, "cancel");
				    	}
	                });
	                
	                $("#ptClose").click(function(){
	                	if(typeof callBack == "function") {
				    		callBack(false, "close");
				    	}
	                });	                
	                $("#ptOk").click(function() {
	                	if(datas.length == 0 && option.xmlStr == null) {
        				    $.ecpPrinter.utils.notify($.ecpPrinter._i18n.qzz.noSchemeInfo);
        				    if(typeof callBack == "function") {
        					    callBack(false, "cancel");
        				    }
        				    return;
        			    }
						option.pageCount = 1;
						option.pageRange = 1;
						option.printScheme = "1";
						option.printgs = "1";
						
						//打印机
						if(printType == "Print") {
							option.printMs = printMs.getValue();
						}
						//打印份数						
	                	option.pageCount = $("#printCount").val();
	                	if(option.pageCount == null 
	                			|| option.pageCount === "" 
	                				|| option.pageCount < 0) {
	                		option.pageCount = 1;
	                	}
		    			
	                    //打印方案
		    			
						option.printScheme = scheme.getValue();
						//要求必须选择打印方案
						if(option.printScheme == null || option.printScheme === "") {
							if(printType == "Print") {
								$.ecpPrinter.utils.notify($.ecpPrinter._i18n.qzz.mustSelPrintScheme);	
							} else {							
								$.ecpPrinter.utils.notify($.ecpPrinter._i18n.qzz.mustSelPrivewScheme);
							}
							//添加回调函数
							if(typeof callBack == "function") {
        					    callBack(false, "cancel");
        				    }
							return false;
						}
						option.faVo = faJson[option.printScheme];
						//打印范围
						if(pr2.value() === true) {
							option.pageRange = 2;
						} else if(pr3.value() === true) {
							option.pageRange = $("#pageSize").val();
							if(option.pageRange === "") {
								//
							    
								if(typeof callBack == "function") {
						    		callBack(false);
						    	}
								return;
							}
						}
						
						
						if(option){
							option.findServerData = option.findServerData;
							option.isPageRange  = option.isPageRange;
						}
						if(option.printScheme != 1 && option != null) {
							option.formatId = null;
							option.reload = true;
						}
						//增加自定义布局参数传入
						//gridid, level, xmlStr, baseFooter, baseHeader, baseTitle, reload, footerHtml			
						$.ecpPrinter.printData(printType, option, callBack);
					});
				     
	    		}
	    		
	    		//获得打印份数.
	    		var print_count = 0;	    		
			    
			    try {				
			    	if(option != null && option.hidePrintCount === true || _gid == null || _gid === 0) {
			    		print_count = null;
			    	} else {
			    		//!isNaN(_typeid) 为数字的时候，有可能是通用实体或业务单据，需要查询打印方案
						if(!isNaN(_typeid)) {
							 var bindId ="com.ygsoft.ecp.app.operator.system.service.context.IXtdyfaContext";
							 var mothed = "getPrintCounts";
							 var bindArray = [_classid, _typeid, (_gid || "") + "", _yhdm];
							 print_count = rs.RemoteService.doPost(bindId, mothed, bindArray);
			    			 
						}
			    	}
			    } catch(e) {
			    	print_count = 0;
			    }
	    		//显示打印份数			    
			    if(print_count == null) {
			    	$("#print_count").css("display","none");
			    } else {
			    	$("#print_count").css("display","");
			    	$("#print_count").html($.ecpPrinter._i18n.qzz.hasPrintCounts.replace("{0}",print_count));
			    }
			    
	    		$("#ecpSchemeDlg").modal();
	    		
				if(_classid === "gris.ywdj") {
					    pr1.disable();
					    pr2.disable();
					    pr3.disable();
					    //隐藏掉
					    $("#r1").css("display","none");
					    $("#r2").css("display","none");
					    $("#r3").css("display","none");
				}
	       	}
		} else {
		    //没有方案的情况下
			option.modelOnly = true;
			$.ecpPrinter.printData(printType, option, callBack);
		}
	};
	/**
	 * 批量打印.
	 * @param {Array} option 批量打印数组
     * @param {String} option.classId 类型id
	 * @param {String} option.typeId 类型id
	 * @param {number} option.gid 单据gid
	 * @param {String} option.format 格式id
	 * @param {boolean} option.noSpwinShow 是否隐藏方案选择窗口 false:显示 true:隐藏
	 * @param {function} callBack 回调函数
	 * @param {function} proEvent 进度事件
	 */
//	$.ecp.batchPrint = function(option, callBack, proEvent, index, optionJson, poption) {
//		if(!(option instanceof Array)) {
//			option = [option];
//		}
//		var cindex = index;
//		if(cindex == null) {
//			cindex = 0;			
//		}
//		var opJson = optionJson;
//		if(opJson == null) {
//			opJson = {};
//		}
//		if(cindex == 0) {
//			var _this = this;
//			new UIDialog('共打印'+option.length+'张单据，是否进行打印？', {
//	            'type': 'question',
//	            'title': '提示',
//	            'buttons': ['是', '否'],
//	            'focus':'是',
//	            'onClose': function (caption) {
//			                   if(caption == '是') {
//				               		var copt = option[cindex];
//				            		if(copt != null) {
//				            			var nsw = copt.spwinShow == false || copt.noSpwinShow == true
//				            			var popt = opJson[copt.typeId];
//				            			if(popt != null) {
//				            				copt.printMs = popt.printMs;				
//				            				//如果原本不显示提示框时
//				            				if(!nsw && copt.typeId == popt.typeId && copt.classId == popt.classId) {
//				            					copt.noSpwinShow = true;
//				            					copt.printgs = popt.printgs;
//				            					copt.faVo = popt.faVo;
//				            					copt.pageRange = popt.pageRange;
//				            					copt.pageCount = popt.pageCount;
//				            				}
//				            			}
//				            			if(nsw && poption != null) {
//				            				//打印机
//				            				copt.printMs = poption.printMs;
//				            				//打印份数
//				            				copt.pageCount = poption.pageCount;
//				            			}
//				            			opJson[copt.typeId] = copt;
//				            			copt.batchPrint = true;
//				            			//循环调用
//				            			$.ecp.print("Print", copt, function(state) {
//				            				if(typeof proEvent == "function") {
//				            					proEvent(option.length, cindex + 1);
//				            				}				
//				            				if(cindex < option.length - 1 && state !== false) {
//				            					setTimeout(function() {
//				            						$.ecp.batchPrint(option, callBack, proEvent, cindex + 1, opJson, copt);
//				            					}, 0);					
//				            				} else {
//				            					if(typeof callBack === "function") {
//				            						callBack(option.length, cindex + 1);
//				            					}
//				            				}
//				            			});
//				            		} else {
//				            			if(typeof callBack === "function") {
//				            				callBack(option.length, cindex + 1);
//				            			}
//				            		}
//			                   } else {
//			                	   if(typeof callBack === "function") {
//			                		   callBack(option.length, 1);
//			                	   } 
//			                   }
//			               }
//			     }).show();
//		} else {
//			var copt = option[cindex];
//			if(copt != null) {
//				var nsw = copt.spwinShow == false || copt.noSpwinShow == true
//				var popt = opJson[copt.typeId];
//				if(popt != null) {
//					copt.printMs = popt.printMs;				
//					//如果原本不显示提示框时
//					if(!nsw && copt.typeId == popt.typeId && copt.classId == popt.classId) {
//						copt.noSpwinShow = true;
//						copt.printgs = popt.printgs;
//						copt.faVo = popt.faVo;
//						copt.pageRange = popt.pageRange;
//						copt.pageCount = popt.pageCount;
//					}
//				}
//				if(nsw && poption != null) {
//					//打印机
//					copt.printMs = poption.printMs;
//					//打印份数
//					copt.pageCount = poption.pageCount;
//				}
//				opJson[copt.typeId] = copt;
//				copt.batchPrint = true;
//				//循环调用
//				$.ecp.print("Print", copt, function(state) {
//					if(typeof proEvent == "function") {
//						proEvent(option.length, cindex + 1);
//					}				
//					if(cindex < option.length - 1 && state !== false) {
//						setTimeout(function() {
//							$.ecp.batchPrint(option, callBack, proEvent, cindex + 1, opJson, copt);
//						}, 0);					
//					} else {
//						if(typeof callBack === "function") {
//							callBack(option.length, cindex + 1);
//						}
//					}
//				});
//			} else {
//				if(typeof callBack === "function") {
//					callBack(option.length, cindex + 1);
//				}
//			}
//		}
//	};	

	return qzz.print.ecpBean;
});